How to get all array items that don't exists in a specific attribute in all documents of a collection in mongodb

Viewed 39

I am new to Nodejs and MongoDB. In one of my tasks, I have a dynamic array of phone numbers like this:

var INPUT_ARRAY = [ "1000000000", "1000000050", "1000000100", "1000000101" ];

this array will contains 2k-3k values. I also have a collection employees with employee details around 100000 documents like given below:

{
  "_id": {
    "$oid": "60536cc1aafebb0d10399df8"
  },
  "phone": "1000000000",
  "first_name": "john",
  "last_name": "doe"
}

I need to match dynamic array values against employee collections and need to return all the phone numbers from dynamic array that don't exists in employees collection.

I searched a lot for this and also checked following questions Compare arrays and Return the Difference MongoDB Find values passed in that don't match

but these question's answer didn't worked for me.

Can somebody please help me to find a performance wise better solution?

Thanks in Advance.

1 Answers

SOLUTION #1:

var INPUT_ARRAY = ["1000000000", "1000000050", "1000000100", "1000000101"]

db.employees.aggregate([
    {
        $group: {
            _id: null,
            phone_numbers: { $push: "$phone" }
        }
    },
    {
        $addFields: {
            missingNumbers: {
                $filter: {
                    input: INPUT_ARRAY,
                    as: "phone_number",
                    cond: {
                        $not: {
                            $in: ["$$phone_number", "$phone_numbers"]
                        }
                    }
                }
            }
        }
    }
]);

SOLUTION #2: As suggested by @Joe in the comments:

var INPUT_ARRAY = ["1000000000", "1000000050", "1000000100", "1000000101"]

db.employees.aggregate([
    {
        $group: {
            _id: null,
            phone_numbers: { $push: "$phone" }
        }
    },
    {
        $addFields: {
            missingNumbers: {
                $setDifference: [INPUT_ARRAY, "$phone_numbers"]
            }
        }
    }
]);

Output:

{
    "_id" : null,
    "phone_numbers" : [
        "1000000000",
        "1000000050",
        "10000060"
    ],
    "missingNumbers" : [
        "1000000100",
        "1000000101"
    ]
}

employees collection

/* 1 createdAt:3/18/2021, 8:37:45 PM*/
{
    "_id" : ObjectId("60536cc1aafebb0d10399df8"),
    "phone" : "1000000000",
    "first_name" : "john",
    "last_name" : "doe"
},

/* 2 createdAt:3/18/2021, 8:37:45 PM*/
{
    "_id" : ObjectId("60536cc1aafebb0d10399df9"),
    "phone" : "1000000050",
    "first_name" : "jane",
    "last_name" : "doe"
},

/* 3 createdAt:3/18/2021, 8:37:45 PM*/
{
    "_id" : ObjectId("60536cc1aafebb0d10399dfa"),
    "phone" : "10000060",
    "first_name" : "joe",
    "last_name" : "doe"
}
Related