In mongodb, is it possible to use $addToSet
to test a certain object field for duplications, rather than the object as a whole?
For instance, when storing cookies found on a webpage, ie:
db.audits.insertOne( { _id: 1, cookies: [{name: "xx", value: "abc", ...}]})
can $push
or $addToSet
be used in a way whereby new objects are considered duplicates if they match the name
field already present in the array? ie:
db.audits.updateOne(
{ _id: 1 },
{ $addToSet: { cookies: { $each: [ {name: "xx", value: "def"}, {name: "yy", value: "abc"} ] } } }
)
desired result is for only {name: "yy",..}
to be added to the array.
2
Answers
One option is to use update with pipeline with
$filter
:See how it works on the playground example
Here is the working example with
update aggregate
:Data:
Aggregate:
Output: