Để lấy đối tượng cụ thể từ mảng đối tượng, hãy sử dụng toán tử vị trí ($). Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> 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 }
Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.getASpecificObjectDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{ "_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 } ] } }
Sau đây là truy vấn để lấy một đối tượng cụ thể từ mảng các đối tượng bên trong tài liệu MongoDB cụ thể -
> db.getASpecificObjectDemo.find({_id:1, "CustomerDetails.CustomerPurchaseDescription.id":101},{_id:0, "CustomerDetails.CustomerPurchaseDescription.$":1});
Điều này sẽ tạo ra kết quả sau -
{ "CustomerDetails" : { "CustomerPurchaseDescription" : [ { "id" : 101, "ProductName" : "Product-2", "Amount" : 10500 } ] } }