Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an array field is a part of another array in MongoDB?

Tags:

mongodb

In this question, Jeff the Bear explained how to search documents with an array

contains 'tag1'
contains ['tag1','tag2'],
contains any of ['tag3', 'tag4']

But how should I do if I want to search documents with an array which is part of another array?

post1.tags = ['tag1']
post2.tags = ['tag1','tag3']
post3.tags = ['tag2','tag4']
post4.tags = ['tag1','tag2','tag3','tag4']

I want to get post1 and post3 because they have tags

contained in ['tag1', 'tag2', 'tag4']

I don't want to get post2 and post4, because tag3 doesn't exist in ['tag1', 'tag2', 'tag4']

In other words, select posts that all elements in its tags array can be found in another conditional array

like image 446
Orion Chang Avatar asked Jan 14 '23 20:01

Orion Chang


1 Answers

7 years later... I found this solution, based on this topic.

I am not sure if it is a good solution, performance-wise, but it looks cleaner than the accepted solution.

db.collection.find({
  tags: {
    "$not": {
      "$elemMatch": {
        "$nin": [
          "tag1",
          "tag2",
          "tag4"
        ]
      }
    }
  }
})
like image 194
Rodrigo Torres Avatar answered Jan 17 '23 06:01

Rodrigo Torres