Reputation: 519
I have a mongodb collection Student
as shown:
[{
"name" : "John",
"age" : 19,
"hobbies" : [
{
"hobbyName" : "Sleeping",
"proficiency": "Expert"
},
{
"hobbyName" : "Coding",
"proficiency": "Beginner"
},
{
"hobbyName": "Googling",
"proficiency": "Expert"
}
]
},
{
"name" : "Michael",
"age" : 22,
"hobbies" : [
{
"hobbyName" : "Eating",
"proficiency": "Expert"
}
]
}]
A student can have many hobbies. For querying with a single hobby, I can simply use Student.find({hobbies.hobbyName: "Coding"})
. But what if I want to find all students with one or more hobbies. Say I want to find all students who have Coding and Sleeping as their hobbies. The query should return all students who have both the hobbies. They may or may not have any other hobby. Thanks for any help!
Upvotes: 0
Views: 24
Reputation: 15227
You can use $all
.
db.Student.find({
"hobbies.hobbyName": {
"$all": [
"Coding",
"Sleeping"
]
}
})
Upvotes: 1