查詢 MongoDB 中具有特定值的所有陣列元素的文件?


你可以使用 find() 來實現。讓我們首先使用文件建立一個集合 -

> db.findDocumentsDemo.insertOne(
   {
      _id: 101,
      "ProductDetails": [
         { "ProductValue":100 },
         { "ProductValue":120 }
      ]
   }
);
{ "acknowledged" : true, "insertedId" : 101 }
> db.findDocumentsDemo.insertOne(
   {
      _id: 102,
      "ProductDetails": [
         { "ProductValue":120},
         { "ProductValue":120 },
         { "ProductValue":120 }
      ]
   }
);
{ "acknowledged" : true, "insertedId" : 102 }

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

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

這將生成以下輸出 -

{
   "_id" : 101,
   "ProductDetails" : [
      {
         "ProductValue" : 100
      },
      {
         "ProductValue" : 120
      }
   ]
}
{
   "_id" : 102,
   "ProductDetails" : [
      {
         "ProductValue" : 120
      },
      {
         "ProductValue" : 120
      },
      {
         "ProductValue" : 120
      }
   ]
}

以下是查詢擁有特定值的陣列所有元素的文件的查詢,這裡值為 ProductValue 120 -

> db.findDocumentsDemo.find({
   "ProductDetails.ProductValue" : {
   },
   "ProductDetails" : {
      $not : {
         $elemMatch : {
            "ProductValue" : {
               $ne : 120
            }
         }
      }
   }
});

這將生成以下輸出 -

{ "_id" : 102, "ProductDetails" : [ { "ProductValue" : 120 }, { "ProductValue" : 120 }, { "ProductValue" : 120 } ] }

更新於: 30-Jul-2019

106 次瀏覽

啟動你的 職業生涯

完成課程獲得認證

開始了
廣告
© . All rights reserved.