Find document with array that contains a specific value
Find document with array that contains a specific value
A favouriteFoods is a simple array of strings, you can try to query that field directly:
PersonModel.find({ favouriteFoods: "sushi" }, ...);
But I’d also suggest to creating the string array explicit in your schema:
person = { name : String, favouriteFoods : [String] }
mongodb is don’t have $contains operator
You can do this below code, The closest analogy to contains that mongo has is $in, using this your query would look like:
PersonModel.find({ favouriteFoods: { "$in" : ["sushi"]} }, ...);
For that situation I feel like $all would be more appropriate. If you are looking for person that is into sushi you do:
PersonModel.find({ favoriteFood : { $all : ["sushi"] }, ...})
For your searching want to filter more like so:
PersonModel.find({ favoriteFood : { $all : ["sushi", "bananas"] }, ...})
Test this : $in is like OR and $all like AND.
https://docs.mongodb.com/manual/reference/operator/query/all/