Comparing two object arrays and check if they have

2019-02-25 07:36发布

问题:

How can I execute a query in MongoDB that returns _id if FirstArray and SecondArray has elements in common in "Name" field?

This is the collection structure:

{
    "_id" : ObjectId("58b8d9e3b2b4e07bff8feed5"),
    "FirstArray" : [ 
        {
            "Name" : "A",
            "Something" : "200 ",
        }, 
        {
               "Name" : "GF",
            "Something" : "100 ",
        } 
    ],
    "SecondArray" : [ 
        {
            "Name" : "BC",
            "Something" : "200 ",
        }, 
        {
               "Name" : "A",
            "Something" : "100 ",
        }
    ]
}

回答1:

3.6 Update:

Use $match with $expr. $expr allows use of aggregation expressions inside $match stage.

db.collection.aggregate([
  {"$match":{
    "$expr":{
      "$eq":[
        {"$size":{"$setIntersection":["$FirstArray.Name","$SecondArray.Name"]}},
        0
      ]
    }
  }},
  {"$project":{"_id":1}}
])

Old version:

You can try $redact with $setIntersection for your query.

$setIntersection to compare the FirstArrays Names with SecondArrays Names and return array of common names documents followed by $size and $redact and compare result with 0 to keep and else remove the document.

db.collection.aggregate(
  [{
    $redact: {
      $cond: {
        if: {
          $eq: [{
            $size: {
              $setIntersection: ["$FirstArray.Name", "$SecondArray.Name"]
            }
          }, 0]
        },
        then: "$$KEEP",
        else: "$$PRUNE"
      }
    }
  }, {
    $project: {
      _id: 1
    }
  }]
)