Home > Blockchain >  MongoDB find value in array that does not exist in database
MongoDB find value in array that does not exist in database

Time:07-25

Here I have an array. Some of the values listed below already exist in MongoDB, but I need the values that do not currently exist in the database

ex: - Values currently in the database

[
    {"id":100},
    {"id":500},
    {"id":606},
    {"id":800}
]

the value I have

let x = [100,300,400,500,606,800];

I need the output to consist of the following values:

300,400

These values need to be added because they do not already exist in the database

CodePudding user response:

 dbo.collection.aggregate([{
                            $group: {
                                _id: null,
                                names: {
                                    "$addToSet": "$uid"
                                }
                            }
                        },
                        {
                            "$replaceRoot": {
                                "newRoot": {
                                    results: {
                                        $filter: {
                                            input: x,
                                            as: "datum",
                                            cond: {
                                                $not: {
                                                    "$setIsSubset": [
                                                        [
                                                            "$$datum"
                                                        ],
                                                        "$names"
                                                    ]
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    ]).toArray(function(err, result) {
                        console.log(result);
                    })
  • Related