0

I am trying to perform an aggregate query in MongoDB. My target is to check if any values within an array exists in another array and conditionally introduce a third variable accordingly.

For example, I have an array A => ["a", "b"] and another array B => ["a", "c", "d"] So in this case as "a" exists in both A & B, they should match.

aggregate.push({
                "$addFields": {
                    "canClaim": {
                        $cond: [{
                            $in: [["a", "b"], ["a", "c", "d"]]
                        }, 1, 0]
                    }
                }
            })
2
  • could you show some example documents? Commented Apr 10, 2022 at 18:58
  • Actually, my real document is different. I just posted a similar simple example. If the above example is acheived, I can change accordingly Commented Apr 10, 2022 at 19:04

1 Answer 1

1

Does this help you?

db.collection.aggregate({
  "$addFields": {
    "c": {
      "$setIntersection": [
        "$a",
        "$b"
      ]
    }
  }
},
{
  "$match": {
    "c.1": {
      "$exists": true
    }
  }
})

Mongo Playground

Sign up to request clarification or add additional context in comments.

1 Comment

Great. $setIntersection is the solution for me. Thanks man

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.