Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

แบบสอบถาม MongoDB เพื่อตั้งค่ารายการย่อยในอาร์เรย์?


คุณสามารถใช้ตัวดำเนินการ $ ตำแหน่ง ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -

> db.demo22.insertOne(
...    {
...       ProductId:101,
...
...       ProductDetails:
...       [
...          {
...             ProductFirstPrice: '35',
...             ProductSecondPrice: '75'
...          },
...          {
...             ProductFirstPrice: '',
...             ProductSecondPrice:''
...          },
...          {
...             ProductFirstPrice: '78',
...             ProductSecondPrice:'24'
...          }
...       ]
...    }
...
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14c0b422d07d3b95082e70")
}

แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -

> db.demo22.find().pretty();

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

{
   "_id" : ObjectId("5e14c0b422d07d3b95082e70"),
   "ProductId" : 101,
   "ProductDetails" : [
      {
         "ProductFirstPrice" : "35",
         "ProductSecondPrice" : "75"
      },
      {
         "ProductFirstPrice" : "",
         "ProductSecondPrice" : ""
      },
      {
         "ProductFirstPrice" : "78",
         "ProductSecondPrice" : "24"
      }
   ]
}

ต่อไปนี้เป็นแบบสอบถาม MongoDB เพื่อตั้งค่ารายการย่อยในอาร์เรย์ -

> db.demo22.update({ "ProductDetails.ProductFirstPrice" : "35" },
... { $set : { "ProductDetails.$.ProductFirstPrice" : "" }}, false, true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -

> db.demo22.find().pretty();

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

{
   "_id" : ObjectId("5e14c0b422d07d3b95082e70"),
   "ProductId" : 101,
   "ProductDetails" : [
      {
         "ProductFirstPrice" : "",
         "ProductSecondPrice" : "75"
      },
      {
         "ProductFirstPrice" : "",
         "ProductSecondPrice" : ""
      },
      {
         "ProductFirstPrice" : "78",
         "ProductSecondPrice" : "24"
      }
   ]
}