How to remove duplicate values inside a list in mongodb

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

I have a mongodb collection . When I do.

db.bill.find({})

I get,



        
4条回答
  •  攒了一身酷
    2021-01-02 21:18

    Mongo 3.4+ has $addFields aggregation stage, which allows you to avoid explicitly listing all the other fields in $project:

    db.bill.aggregate([
        {"$addFields": {
            "bill_codes": {"$setUnion": ["$bill_codes", []]}
        }}
    ])
    

    Just for reference, here is another (more lengthy) way that uses replaceRoot and also doesn't require listing all possible fields:

    db.bill.aggregate([
        {'$unwind': {
            'path': '$bill_codes',
            // output the document even if its list of books is empty
            'preserveNullAndEmptyArrays': true
        }},
        {'$group': {
            '_id': '$_id',
            'bill_codes': {'$addToSet': '$bill_codes'},
            // arbitrary name that doesn't exist on any document
            '_other_fields': {'$first': '$$ROOT'},
        }},
        {
          // the field, in the resulting document, has the value from the last document merged for the field. (c) docs
          // so the new deduped array value will be used
          '$replaceRoot': {'newRoot': {'$mergeObjects': ['$_other_fields', "$$ROOT"]}}
        },
        {'$project': {'_other_fields': 0}}
    ])    
    

提交回复
热议问题