Wai_Kun
(Wai Kun)
June 28, 2022, 10:30pm
1
Hey, thank you in advance for reading this post. I basically have data like this:
{
"fruits": {
"banana": [{
"name": "goodBanana",
"ripe": true
}, {
"name": "badBanana",
"ripe": false
}]
}
}
I would like to find documents where there are “goodBanana” in their array of “banana”. I am experimenting with the $in operator but I am having trouble using objects in the expression field. Please let me know the best practice to query this type of data.
Thank you.
1 Like
Wai_Kun
(Wai Kun)
June 28, 2022, 10:54pm
2
I just discovered a solution, I used $elemmatch in this fashion:
fruits: { $elemMatch: {name: "goodBanana"}}
That appeared to have worked, I am not sure if it’s the optimal solution though.
you can try to use $elemMatch operator:
db.test.find({“fruits.banana”:{$elemMatch: {“name”:“goodBanana”}}})
Wai_Kun
(Wai Kun)
June 28, 2022, 10:56pm
4
Thank you, I just solved it just now! The timing. I still appreciate your help.
steevej
(Steeve Juneau)
June 29, 2022, 12:14am
5
The following should work:
c.find( { "fruits.banana.name" : "goodBanana" } )
You would use $in when you have a list rather than a single value like:
c.find( { "fruits.banana.name" : { "$in" : [ "rottenBanana", "badBanada" ] } } )
You would use $elemMatch when wanting multiple condition to be true for the same element like:
c.find( { "fruits.banana" : { "$elemMatch" : { "name" : "goodBanana" , "ripe" : "false" } } } )
2 Likes
system
(system)
Closed
July 4, 2022, 12:15am
6
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.