For anyone new to MongoDB and isn't familiar with constructing MongoDB JSON query objects inside the find* methods, you can leverage the mongoose Query Builders. These are great for newcomers or to encourage consistent querying within your team.
Given the following documents:
{
"_id": "65440e1e5d9811753b6be8e1",
"favoriteFoods": [ "corn", "sushi", "pasta" ],
},
{
"_id": "6545612721b99c8cff188a0a",
"favoriteFoods": [ "eggs", "pizza", "rice" ],
}
You can chain the where() and in() methods to match the specified documents:
const person = await PersonModel.find().where('favoriteFoods').in(['sushi']);
// Returns
[
{
"_id": "65440e1e5d9811753b6be8e1",
"favoriteFoods": [ "corn", "sushi", "pasta" ],
}
]
const person = await PersonModel.find().where('favoriteFoods').in(['sushi', 'pizza']);
// Returns
[
{
"_id": "65440e1e5d9811753b6be8e1",
"favoriteFoods": [ "corn", "sushi", "pasta" ],
},
{
"_id": "6545612721b99c8cff188a0a",
"favoriteFoods": [ "eggs", "pizza", "rice" ],
}
]
A full list of Query Builder methods can be found here.