Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an array field contains a unique value or another array in MongoDB?

Tags:

mongodb

People also ask

How do you check if an array contains a value in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }

How do I search an array in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.

How do I use elemMatch in MongoDB?

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. If you specify only a single <query> condition in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch , $elemMatch can be omitted.

How do you make an array unique in MongoDB?

To get unique values within two arrays in a document, use a $setUnion in aggregate(). The $setUnion takes two or more arrays and returns an array containing the elements that appear in any input array.


Try this out:

db.blogpost.find({ 'tags' : 'tag1'}); //1
db.blogpost.find({ 'tags' : { $all : [ 'tag1', 'tag2' ] }}); //2
db.blogpost.find({ 'tags' : { $in : [ 'tag3', 'tag4' ] }}); //3

My experience is that for (2) the following solution is much faster than the one with "$all":

db.blogpost.find({ $and: [ {tags: 'tag1'} ,{tags: 'tag2'} ] });

but to be honest, I do not not why. I would be interested in, if anyone knows.