Find document with array that contains a specific value

Ludwig Magnusson picture Ludwig Magnusson · Aug 9, 2013 · Viewed 505.6k times · Source

If I have this schema...

person = {
    name : String,
    favoriteFoods : Array
}

... where the favoriteFoods array is populated with strings. How can I find all persons that have "sushi" as their favorite food using mongoose?

I was hoping for something along the lines of:

PersonModel.find({ favoriteFoods : { $contains : "sushi" }, function(...) {...});

(I know that there is no $contains in mongodb, just explaining what I was expecting to find before knowing the solution)

Answer

JohnnyHK picture JohnnyHK · Aug 9, 2013

As favouriteFoods is a simple array of strings, you can just query that field directly:

PersonModel.find({ favouriteFoods: "sushi" }, ...);

But I'd also recommend making the string array explicit in your schema:

person = {
    name : String,
    favouriteFoods : [String]
}

The relevant documentation can be found here: https://docs.mongodb.com/manual/tutorial/query-arrays/