Let’s say I have the following documents:
{
title: 'Some title',
items: [1,5,9,4]
}
{
title: 'Some title',
items: [5,7]
}
{
title: 'Some title',
items: [1,2]
}
I need to get a documents where items have 5. So I make the following query in mongoose:
Model.find({items: {$in: [5]}}, function (err, docs) {
// docs.length == 2
});
And I’m getting it. But I’ve found that if I make the follows query then I get the same:
Model.find({items: 5}, function (err, docs){
// docs.length == 2
});
Is is correct to use the second approach to find docs in my case?
Use
$inwhen you want to find the docs whereitemscontains any one of a set of values; if you want the docs whereitemscontains a specific value, use a simple query object like{items: 5}.So while, as you found, you can use
$into match against a single value, it’s more naturally expressed asModel.find({items: 5}, ...);