Ahsan Aasim
Ahsan Aasim

Reputation: 1307

mongodb using $in for matching array with array inside aggregate

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]
                    }
                }
            })

Upvotes: 0

Views: 192

Answers (1)

Tobias S.
Tobias S.

Reputation: 23825

Does this help you?

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

Mongo Playground

Upvotes: 1

Related Questions