removing duplicate array values from mongodb

前端 未结 2 823
灰色年华
灰色年华 2021-01-14 14:55

In mongodb I have collection where arrays has duplicate entries like

{
    \"_id\": ObjectId(\"57cf3cdd5f20a3b0ba009777\"),
    \"Chat\": 6,
    \"string\":          


        
2条回答
  •  终归单人心
    2021-01-14 15:23

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

    collection.aggregate([
        {"$addFields": {
            "string": {"$setUnion": ["$string", []]}
        }}
    ])
    

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

    collection.aggregate([
        {'$unwind': {
            'path': '$string',
            // output the document even if its list of books is empty
            'preserveNullAndEmptyArrays': true
        }},
        {'$group': {
            '_id': '$_id',
            'string': {'$addToSet': '$string'},
            // 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}}
    ])    
    

提交回复
热议问题