BlackH3art
BlackH3art

Reputation: 596

How can I receive an array, comparing two other arrays using aggregation framework?

How am i supposed to build my pipeline in MongoDB if, lets say i got this collection:

[
 {_id: 1, field: "somevalue", array: ["123", "abc", "456", "def"]},
 {_id: 2, field: "somevalue", array: ["zxc", "abc", "vbn", "jkl"]},
 {_id: 3, field: "somevalue", array: ["fgh", "asd", "456", "def"]}
]

And I want receive in a new field, new array of values that matches values from my current array?

Lets say I got this array which i want to campare with:

[ "abc", "456"]

So I'm expecting to receive this:

[
 {_id: 1, field: "somevalue", array: ["123", "abc", "456", "def"], myNewArray: ["abc", "456"]},
 {_id: 2, field: "somevalue", array: ["zxc", "abc", "vbn", "jkl"], myNewArray: ["abc"]},
 {_id: 3, field: "somevalue", array: ["fgh", "asd", "456", "def"], myNewArray: ["456"]}
]

How exactly can I build my pipeline to receive this?

Upvotes: 0

Views: 19

Answers (1)

matthPen
matthPen

Reputation: 4343

You can simply use $setIntersection operator to keep only elements present in your array parameter.

db.collection.aggregate([
  {
    "$addFields": {
      "newArray": {
        $setIntersection: [
          [
            "abc",
            "456"
          ],
          "$array"
        ]
      }
    }
  }
])

You can test it here

Upvotes: 1

Related Questions