Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two object arrays and check if they have common elements

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 ",
        }
    ]
}
like image 663
Oper Avatar asked Mar 03 '17 16:03

Oper


1 Answers

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
    }
  }]
)
like image 131
s7vr Avatar answered Oct 19 '22 23:10

s7vr