Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo Query a nested field within an array.

Tags:

mongodb

I have a document with the following structure: {_id: 'fkwjefioew', genres: [{_id: 'fewkjfewf', 'name': "Shooter"}, {...}, ...]} I need to be able to query using mongo's $in to see if the doc has the genre name of the passed parameter. For example, if I passed the parameter of "Shooter" to the query, I would want all the documents where one of the objects within that documents generes array holds the name "Shooter". What would be the easiest way to achieve this? Thanks!

like image 757
TDmoneybanks Avatar asked Feb 16 '26 09:02

TDmoneybanks


1 Answers

You would want to use $elemMatch for this.

{"genres": { "$elemMatch" :  {"name": "Shooter"} } }
// or
{"genres": { "$elemMatch" :  {"name": { "$in": ["Shooter"] } } } }

https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

You could also use the mongodb dot notation and it will pretty much work like you would except:

{"genres.name": "Shooter"}
// or
{"genres.name": { "$in": ["Shooter"]}}

Mongodb knows how to interpret this in case genres is an array. Just keep in mind that the dot notation query is slightly ambiguous, since it will will also match to the name property in case the genres property is not an array. For example, this doc would match:

{"genres": { "name": "Shooter" } }

In all cases you can index the name property in the genres array and the index would be used for the lookups.

db.collection.createIndex({'genres.name': 1})

https://docs.mongodb.com/manual/reference/glossary/#term-dot-notation

https://docs.mongodb.com/manual/reference/operator/query/in/

like image 126
Willem D'Haeseleer Avatar answered Feb 19 '26 20:02

Willem D'Haeseleer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!