I have a mongodb collection . When I do.
db.bill.find({})
I get,
MongoDB 4.2 collection updateMany method's update parameter can also be an aggregation pipeline (instead of a document). The pipeline supports $set
, $unset
and $replaceWith
stages. Using the $setIntersection
aggregation pipeline operator with the $set
stage, you can remove the duplicates from an array field and update the collection in a single operation.
An example:
arrays collection:
{ "_id" : 0, "a" : [ 3, 5, 5, 3 ] }
{ "_id" : 1, "a" : [ 1, 2, 3, 2, 4 ] }
From the mongo shell:
db.arrays.updateMany(
{ },
[
{ $set: { a: { $setIntersection: [ "$a", "$a" ] } } }
]
)
The updated arrays collection:
{ "_id" : 0, "a" : [ 3, 5 ] }
{ "_id" : 1, "a" : [ 1, 2, 3, 4 ] }
The other update methods, update()
, updateOne()
and findAndModify()
also has this feature.