如何從特定 MongoDB 文件中的物件陣列中獲取特定物件?
要從物件陣列中獲取特定物件,請使用定位運算子($)。我們首先建立一個包含文件的集合 -
> db.getASpecificObjectDemo.insertOne( ... { ... _id :1,f ... "CustomerName" : "Larry", ... "CustomerDetails" : { ... "CustomerPurchaseDescription": [{ ... id :100, ... "ProductName" : "Product-1", ... "Amount":10000 ... },{ ... id :101, ... "ProductName" : "Product-2", ... "Amount":10500 ... }, ... { ... id :102, ... "ProductName" : "Product-3", ... "Amount":10200 ... } ... ] ... } ... } ... ); { "acknowledged" : true, "insertedId" : 1 }
以下是使用 find() 方法從集合顯示所有文件的查詢 -
> db.getASpecificObjectDemo.find().pretty();
這將產生以下輸出 -
{ "_id" : 1, "CustomerName" : "Larry", "CustomerDetails" : { "CustomerPurchaseDescription" : [ { "id" : 100, "ProductName" : "Product-1", "Amount" : 10000 }, { "id" : 101, "ProductName" : "Product-2", "Amount" : 10500 }, { "id" : 102, "ProductName" : "Product-3", "Amount" : 10200 } ] } }
以下是從特定 MongoDB 文件中的物件陣列獲取特定物件的查詢 -
> db.getASpecificObjectDemo.find({_id:1, "CustomerDetails.CustomerPurchaseDescription.id":101},{_id:0, "CustomerDetails.CustomerPurchaseDescription.$":1});
這將產生以下輸出 -
{ "CustomerDetails" : { "CustomerPurchaseDescription" : [ { "id" : 101, "ProductName" : "Product-2", "Amount" : 10500 } ] } }
廣告