Monday, March 29, 2021

How to find exact embedded documents using $elemMatch?

 Let's say we have below dataset:

[{

name : "Simon"

hobbies : [

{ title : "badminton", frequency : 2 } ,

{ title : "Swimming", frequency : 1 } 

]

}, 

{

name : "Max"

hobbies : [

{ title : "badminton", frequency : 1 } ,

{ title : "Swimming", frequency : 2 } 

]

},]


Our goal is to find a person who likes badminton and 2 badminton playings frequently.


If you using the below query, it will return Simon and Max.


db.people.find({"hobbies .title":"badminton","hobbies.frequency ":2});

db.people.find({$and: [{"hobbies .title":"badminton"},{"hobbies .frequency ":2}]})


Max returned in the search result because he has a badminton hobby and frequency 2 in swimming.


To search for the exact person who likes badminton and 2 badminton playing frequently, you can use $elemMatch operator.


db.people.find({"hobbies":{$elemMatch: {"title":"badminton","frequency ":2}}})

No comments:

Post a Comment