Find an object in nested array of object

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

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”}}})

Thank you, I just solved it just now! The timing. I still appreciate your help.

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

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.