skip to Main Content

I have an array like this

let arr = [a,b,c]

and a collection like this

{val:a},{val:b}

I want to know that document with val=c is not in the collection.

2

Answers


  1. One option is:

    let arr = ['a', 'b', 'c'];
    db.collection.aggregate([
      {$group: {_id: null, vals: {$addToSet: "$val"}}},
      {$project: {_id: 0, notIncluded: {$setDifference: [arr, "$vals"]}}}
    ])
    

    See how it works on the playground example

    Login or Signup to reply.
  2. You could use filter, and a findOne for each value like:

    let arr = ["a","b","c"];
    let notfound = arr.filter((value) => db.collection.findOne({val:value}) === null)
    

    Or you could use distinct with a filter:

    let arr = ["a","b","c"]
    let existing = db.collection.distinct("val")
    let notfound = arr.filter((value)=> existing.indexOf(value) == -1)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search