用於在陣列中設定子項的 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"
      }
   ]
}

更新時間:2020 年 4 月 1 日

205 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告