what is $elemMatch in mongodb? how to use $elemMatch?



$elemMatch is an operator. it is used to find the documents having array fields containing multiple elements.

for example 1:-

i have document in which I want to find document where results greater than 80 and less than 85.
{ _id: 1, results: [ 82, 85, 88 ] }
{ _id: 2, results: [ 75, 88, 89 ] }

write query using $elemMatch like:-

here score is the collection containing these documents.

db.score.find({results:{$elemMatch:{$gt:80,$lt:85}}})

it returns first document because $gt:80 means greater than 80 which is 82 and $lt:85 means less than 85 which is 85. that's why document first will be returned.

for example 2:-

{ _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 } ] }
{ _id: 2, results: [ { product: "abc", score: 8 }, { product: "xyz", score: 7 } ] }
{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] }
find documents where product is "xyz" and score is greater or equal to 8.

to do so, write query using $elemMatch like:-

here survey is the collection containing these documents.

db.survey.find({results:{
 $elemMatch:{product:"xyz",score:{$gte:8}}
}})

here using $gte(greater than or equal to) operator which matches score whose value greater than or equal to 8.





No comments:

Post a Comment