Java_byte
Java_byte

Reputation: 49

DIfference between mentioned two queries in mongoDB

Please explain the difference between two queries mentioned below. I am getting output for first query but no output for second. Thanks in advance.

Table data:

> db.inventory.find()
{ "_id" : ObjectId("5911ce218c302726ff998853"), "item" : "journal", "instock" : [ { "warehouse" : "A", "qty" : 5 }, { "warehouse" : "C", "qty" : 15 } ] }
{ "_id" : ObjectId("5911ce218c302726ff998854"), "item" : "notebook", "instock" : [ { "warehouse" : "C", "qty" : 5 } ] }
{ "_id" : ObjectId("5911ce218c302726ff998855"), "item" : "paper", "instock" : [ { "warehouse" : "A", "qty" : 60 }, { "warehouse" : "B", "qty" : 15 } ] }
{ "_id" : ObjectId("5911ce218c302726ff998856"), "item" : "planner", "instock" : [ { "warehouse" : "A", "qty" : 40 }, { "warehouse" : "B", "qty" : 5 } ] }
{ "_id" : ObjectId("5911ce218c302726ff998857"), "item" : "postcard", "instock" : [ { "warehouse" : "B", "qty" : 15 }, { "warehouse" : "C", "qty" : 35 } ] }
{ "_id" : ObjectId("5911ce948c302726ff998858"), "item" : "journal", "instock" : [ { "warehouse" : "A", "qty" : 5 } ] }

Query 1:

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

Output:

{ "_id" : ObjectId("5911ce218c302726ff998853"), "item" : "journal", "instock" : [ { "warehouse" : "A", "qty" : 5 }, { "warehouse" : "C", "qty" : 15 } ] }
{ "_id" : ObjectId("5911ce948c302726ff998858"), "item" : "journal",    "instock" : [ { "warehouse" : "A", "qty" : 5 } ] }

Query 2:

> db.inventory.find( { "instock.qty": { $elemMatch: { $gt: 10, $lte: 20 } } } )

Output:

No output

Upvotes: 1

Views: 96

Answers (1)

s7vr
s7vr

Reputation: 75914

From the docs

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

Point to note the field should be an array.

The correct syntax for second query for querying on embedded fields qty inside array is

db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )

You should have a document like below with qty as array field for your current second query to return results.

{ "item" : "journal", "instock" : [ { "qty" : [ 5, 15 ] }, { "warehouse" : "A", "qty" : 5 }, { "warehouse" : "C", "qty" : 15 }] }

Upvotes: 1

Related Questions