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

前端 未结 3 1229
独厮守ぢ
独厮守ぢ 2020-12-11 10:50

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

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


        
相关标签:
3条回答
  • 2020-12-11 11:19

    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"
            ]
          }
        }
      }
    })
    
    0 讨论(0)
  • 2020-12-11 11:20

    You can use aggregation framework to do this. Given the following data

    > db.post.find()
    { "_id" : 1, "tags" : [ "tag1" ] }
    { "_id" : 2, "tags" : [ "tag1", "tag3" ] }
    { "_id" : 3, "tags" : [ "tag2", "tag4" ] }
    { "_id" : 4, "tags" : [ "tag1", "tag2", "tag3", "tag4" ] }
    

    the aggregation query

    db.post.aggregate({
      $project: {
        _id: 1,
        tags: 1,
        killFlag: {
          $const: [true, false]
        }
      }
    }, {
      $unwind: "$tags"
    }, {
      $unwind: "$killFlag"
    }, {
      $match: {
        $nor: [{
            tags: {
              $in: ['tag1', 'tag2', 'tag4']
            },
            killFlag: true
          }
        ]
      }
    }, {
      $group: {
        _id: "$_id",
        tags: {
          $addToSet: "$tags"
        },
        killFlag: {
          $max: "$killFlag"
        }
      }
    }, {
      $match: {
        killFlag: false
      }
    }, {
      $project: {
        _id: 1,
        tags: 1
      }
    })
    

    would give you

    {
      "result": [{
          "_id": 3,
          "tags": [
              "tag4",
              "tag2"
          ]
        }, {
          "_id": 1,
          "tags": [
              "tag1"
          ]
        }
      ],
      "ok": 1
    }
    
    0 讨论(0)
  • 2020-12-11 11:22

    I had a similiar task, and what is working for me:

    db.collection.find({ tags: { "$all":[ tag1", tag2", "tag4"] }})

    maybe for someone this will be helpfull sollution founded in docs https://docs.mongodb.com/manual/tutorial/query-arrays/#specify-multiple-criteria-for-array-elements

    0 讨论(0)
提交回复
热议问题