查詢MongoDB中使用條件插入陣列元素?


我們首先使用文件建立一個集合 -

>db.demo11.insertOne({"ListOfStudent":[{"StudentName":"Chris","ListOfScore":[76,67,54,89]}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f6e34d7df943a7cec4fa1")
}

以下是用 find() 方法顯示集合中所有文件的查詢 -

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

這將產生以下輸出 -

{
   "_id" : ObjectId("5e0f6e34d7df943a7cec4fa1"),
   "ListOfStudent" : [
      {
         "StudentName" : "Chris",
         "ListOfScore" : [
            76,
            67,
            54,
            89
         ]
      }
   ]
}

以下是使用條件插入陣列元素的查詢 -

> db.demo11.update( {"ListOfStudent.StudentName":"Chris"}, {$push:{"ListOfStudent.$.ListOfScore":98}} );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

讓我們再次檢查文件 -

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

這將產生以下輸出 -

{
   "_id" : ObjectId("5e0f6e34d7df943a7cec4fa1"),
   "ListOfStudent" : [
      {
         "StudentName" : "Chris",
         "ListOfScore" : [
            76,
            67,
            54,
            89,
            98
         ]
      }
   ]
}

更新於: 2020-04-01

603 次瀏覽

開啟您的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.