Home > database >  MongoDb : query to match in same embedded document
MongoDb : query to match in same embedded document

Time:08-25

Help me to match in single embedded document of both conditions.

db.inventory.insertOne([
...     { "item": "journal", "instock": [ { "warehouse": "A", "qty": 5 }, { "warehouse": "C", "qty": 15 } ] },
...     { "item": "notebook", "instock": [ { "warehouse": "C", "qty": 5 } ] },
...     { "item": "paper", "instock": [ { "warehouse": "A", "qty": 60 }, { "warehouse": "B", "qty": 15 } ] },
...     { "item": "planner", "instock": [ { "warehouse": "A", "qty": 40 }, { "warehouse": "B", "qty": 5 } ] },
...     { "item": "postcard", "instock": [ { "warehouse": "B","qty": 15 }, { "warehouse": "C", "qty": 35 } ] }
... ])

Expected to return single document which match exactly as quered but returns two.

db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )
{ "_id" : ObjectId("63061a1bb87c1278047a2717"), "item" : "journal", "instock" : [ { "warehouse" : "A", "qty" : 5 }, { "warehouse" : "C", "qty" : 15 } ] }
{ "_id" : ObjectId("63061a1bb87c1278047a271a"), "item" : "planner", "instock" : [ { "warehouse" : "A", "qty" : 40 }, { "warehouse" : "B", "qty" : 5 } ] }

CodePudding user response:

You need to perform the following query:

db.inventory.find({
  instock: { $elemMatch: { qty: 5, warehouse: 'A' } }
});

Documentation for reference: https://www.mongodb.com/docs/v5.0/tutorial/query-array-of-documents/#a-single-nested-document-meets-multiple-query-conditions-on-nested-fields

  • Related