Aggregation between a MongoDB collection and an external array

I'm looking for a method for join a collection and a external array of strings (with codes), that returns another string array with all codes of first array that aren't included in the collection.

The collection sample:

[{
    _id:ObjectId("61bf57bc9d1f93b7ae5fa785"),
    "Movie": {
        "Code": "123",
        "OriginalTitle": "Title 1",
        "Year": 2021
     }},{
    _id:ObjectId("61bf57bc9d1f93b7ae5fa786"),
    "Movie": {
        "Code": "124",
        "OriginalTitle": "Title 2",
        "Year": 2021
     }},{
    _id:ObjectId("61bf57bc9d1f93b7ae5fa787"),
    "Movie": {
        "Code": "125",
        "OriginalTitle": "Title 3",
        "Year": 2021
     }},{
    _id:ObjectId("61bf57bc9d1f93b7ae5fa788"),
    "Movie": {
        "Code": "126",
        "OriginalTitle": "Title 4",
        "Year": 2021
     }
 }]

the external array:

const codes = ["125", "127", "128", "129"];

the aggregation must compare "Movie.Code" with the array and returns another array with the next values:

returnCodes = ["127", "128", "129"];

How can I make it?


Solution 1:

Maybe this:

db.collection.aggregate([  
  {
    $group: {
      _id: null,
      Code: { $push: "$Movie.Code" }
    }   
  },   
  {
    $project: {
      returnCodes: {
        $filter: {
          input: codes ,
          cond: { $not: { $in: [ "$$this", "$Code" ] } }
        }
      }
    }   
  } 
]).toArray().shift().returnCodes

Of course, you could do it also in Javascript:

const codes = ["125", "127", "128", "129"];
const coll = db.collection.find({}, { Code: "$Movie.Code" }).toArray().map(x => x.Code);

returnCodes = codes.filter(x => !coll.includes(x));