How to remove duplicate values inside a list in mongodb

后端 未结 4 1213
迷失自我
迷失自我 2021-01-02 20:35

I have a mongodb collection . When I do.

db.bill.find({})

I get,



        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-02 21:23

    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.

提交回复
热议问题