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

Mongodb

Mongodb Problem Overview


I am using mongodb now.

I have a blogpost collection, and it has a tags field which is an array, e.g.

blogpost1.tags = ['tag1', 'tag2', 'tag3', 'tag4', 'tag5']
blogpost2.tags = ['tag2', 'tag3']
blogpost3.tags = ['tag2', 'tag3', 'tag4', 'tag5']
blogpost4.tags = ['tag1', 'tag4', 'tag5']

How can I do these search

  1. contains tag1
  2. contains ['tag1','tag2']
  3. contains any of ['tag3', 'tag4']

Mongodb Solutions


Solution 1 - Mongodb

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

Solution 2 - Mongodb

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionguilin 桂林View Question on Stackoverflow
Solution 1 - MongodbJeff the BearView Answer on Stackoverflow
Solution 2 - MongodbheinobView Answer on Stackoverflow