Find all duplicate documents in a MongoDB collection by a key field

后端 未结 5 486
温柔的废话
温柔的废话 2020-11-28 22:00

Suppose I have a collection with some set of documents. something like this.

{ \"_id\" : ObjectId(\"4f127fa55e7242718200002d\"), \"id\":1, \"name\" : \"foo\"         


        
5条回答
  •  悲哀的现实
    2020-11-28 22:23

    Note: this solution is the easiest to understand, but not the best.

    You can use mapReduce to find out how many times a document contains a certain field:

    var map = function(){
       if(this.name) {
            emit(this.name, 1);
       }
    }
    
    var reduce = function(key, values){
        return Array.sum(values);
    }
    
    var res = db.collection.mapReduce(map, reduce, {out:{ inline : 1}});
    db[res.result].find({value: {$gt: 1}}).sort({value: -1});
    

提交回复
热议问题