Reputation: 189
I have an array:
let arr=["v1","v2","v3"];
This array is condition for my query in mongodb. The query in nodejs is:
cursor = await myCollection.find({"attribute":{ $in: arr}},{_id:0,title:1});
The result doesn't have the fields are in the projection. But when I change $in and use $all,the query brings the title field.
Help me please
Upvotes: 1
Views: 750
Reputation: 3185
In a very simple words:
Difference: 1
{ $in: ["v1","v2","v3"] }
works as OR condition and { $all: ["v1","v2","v3"] }
works as AND conditions.
With $in if any of value from v1 , v2 and v3 match with "attribute" value then your will get document in result.
With $all if all value from v1, v2, and v3 must exist at "attribute" value then only you will get result document.
Difference: 2
$all should be used only on array attribute as if you will use $all on string attribute with two or more value in array then will always get empty result .
$in can be useful with both type of attributes "array" and "String" as in case of String attribute if any of the value matched with value from array then you will get respective document in result.
Upvotes: 1
Reputation: 170
In $in operator selects the documents where the value of a field equals any value in the specified array, according to mongoDB documentation.
In $all operator selects the documents where the value of a field is an array that contains all the specified elements, according to mongoDB documentation.
In your case if you use $all instead of using $in, this query check all the elements in your array.
Upvotes: 1