Danielyan
Danielyan

Reputation: 1

Is there any way to find which elements of given array is not in DB

I have a document:

    [
        {name: "Jack", age: "18"},
        {name: "Mark", age: "24"},
        {name: "Jane", age: "16"},
        ...
    ]

And I have a list of names:

    ["Mark", "Bob", "Jack"]

Is there any way to find which names are not in document? In my case it will be ["Bob"].

Upvotes: 0

Views: 45

Answers (1)

sushant mehta
sushant mehta

Reputation: 1274

Please try below solution using the aggregate pipeline.

db.collection.aggregate([
  {
    $group: {
      _id: null,
      names: {
        $push: "$name"
      }
    }
  },
  {
    $project: {
      leftNames: {
        $setDifference: [
          [
            "Mark",
            "Bob",
            "Jack"
          ],
          "$names"
        ]
      }
    }
  }
])

Upvotes: 1

Related Questions