-1

How do we find keys which do not exist in collection.
Given an input list of keys ['3321', '2121', '5647'] , i want to return those that do not exist in the collection :

{ "_id" : { "$oid" : "5e2993b61886a22f400ea319" }, "scrip" : "5647" }
{ "_id" : { "$oid" : "5e2993b61886a22f400ea31a" }, "scrip" : "3553" }

So the expected output is ['3321', '2121']

IUnknown
  • 9,301
  • 15
  • 50
  • 76

1 Answers1

1

This aggregation gets the desired output (works with MongoDB version 3.4 or later):

INPUT_ARRAY = ['3321', '2121', '5647']

db.test.aggregate( [
{
  $match: {
    scrip: {
        $in: INPUT_ARRAY
    }
  }
},
{ 
  $group: { 
      _id: null, 
      matches: { $push: "$scrip" } 
  } 
},
{ 
  $project: {
      scrips_not_exist: { $setDifference: [ INPUT_ARRAY, "$matches" ] },
      _id: 0
  } 
}
] )

The output:

{ "scrips_not_exist" : [ "3321", "2121" ] }
prasad_
  • 12,755
  • 2
  • 24
  • 36