user3470294
user3470294

Reputation: 190

mongodb compare two arrays and return difference

I have a mongoDB collection as below


{
_id: 1
"probes": ["A", "B"],
"result": ["A", "B","C","D"],
}

I want to compare probes with result and create a new field called exception

{
_id: 1
"probes": ["A", "B"],
"result": ["A", "B","C","D"],
"exception" : ["C","D"]
}

if the exception field is already present, then it has to be overwritten.

Any help is greatly appreciated.

Upvotes: 1

Views: 233

Answers (1)

mickl
mickl

Reputation: 49945

You can use $setDifference operator:

db.collection.aggregate([
    {
        $addFields: {
            exception: {
                $setDifference: [ "$result", "$probes" ]
            }
        }
    }
])

Mongo Playground

Upvotes: 1

Related Questions