如何從 MongoDB 中的嵌入陣列獲取特定元素?


要獲取特定元素,請使用帶點表示法的 $ 匹配。我們建立一個包含文件的集合 -

> db.demo641.insert(
...    {
...       ProductId:101,
...       "ProductInformation":
...      (                            [
...          {
...             ProductName:"Product-1",
...             "ProductPrice":1000
...          },
...          {
...             ProductName:"Product-2",
...             "ProductPrice":500
...          },
...          {
...             ProductName:"Product-3",
...             "ProductPrice":2000
...          },
...          {
...             ProductName:"Product-4",
...             "ProductPrice":3000
...          }
...       ]
...    }
... );
WriteResult({ "nInserted" : 1 })

藉助 find() 方法顯示集合中的所有文件 -

> db.demo641.find();

這將生成以下輸出 -

{
   "_id" : ObjectId("5e9c31d46c954c74be91e6e2"), "ProductId" : 101, "ProductInformation" :
   [
      { "ProductName" : "Product-1", "ProductPrice" : 1000 },
      { "ProductName" : "Product-2", "ProductPrice" : 500 },
      { "ProductName" : "Product-3", "ProductPrice" : 2000 },
      { "ProductName" : "Product-4", "ProductPrice" : 3000 }
   ] 
}

以下是 MongoDB 中從嵌入陣列中獲取特定元素的查詢

> db.demo641.aggregate([
... {$unwind: "$ProductInformation"},
... {$match: { "ProductInformation.ProductPrice": {$in :[1000, 2000]}} },
... {$project: {_id: 0, ProductInformation: 1} }
... ]).pretty();

這將生成以下輸出 -

{
   "ProductInformation" : {
      "ProductName" : "Product-1",
      "ProductPrice" : 1000
   }
}
{
   "ProductInformation" : {
      "ProductName" : "Product-3",
      "ProductPrice" : 2000
   }
}

更新日期: 2020 年 5 月 12 日

359 次瀏覽

Kickstart 你的 職業

完成課程獲得認證

開始使用
廣告
© . All rights reserved.