9

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 Answer 1

18

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
    }
  }]
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.