删除除最新文档之外的所有重复项

时间:2016-03-09 13:11:15

标签: mongodb mongodb-query aggregation-framework

我想清除集合中所有重复的特定字段。只留下最重复的条目。

这是我的汇总查询,它非常适合查找重复项:

db.History.aggregate([
  { $group: {
_id: { name: "$sessionId" },  
uniqueIds: { $addToSet: "$_id" },
count: { $sum: 1 } 
  } }, 
  { $match: { 
count: { $gte: 2 } 
  } },
  { $sort : { count : -1} }
 ],{ allowDiskUse:true,
  cursor:{}});

唯一的问题是我还需要执行删除查询并为每个重复项保留最年轻的条目(由字段'timeCreated'确定:

"timeCreated" : ISODate("2016-03-07T10:48:43.251+02:00")

我到底该怎么做?

1 个答案:

答案 0 :(得分:1)

我个人会利用ObjectId值本身“单调”或因此“价值不断增加”的事实,这意味着“最年轻”或“最新”将出现在自然排序列表的末尾

因此,不要强制聚合管道进行排序,最合乎逻辑且最有效的方法是在处理每个响应时对每个文档返回的唯一_id值列表进行排序。

所以基本上使用你必须找到的列表:

  

Remove Duplicates from MongoDB

实际上是我的回答(这是你本周引用的第二个人,但是没有收到有用的投票!嗯!),其中只是一个简单的.sort()返回数组的游标迭代:

使用_id值

var bulk = db.History.initializeOrderedBulkOp(),
    count = 0;

// List "all" fields that make a document "unique" in the `_id`
// I am only listing some for example purposes to follow
db.History.aggregate([
    { "$group": {
        "_id": "$sessionId",
        "ids": { "$push": "$_id" }, // _id values are already unique, so $addToSet adds nothing
        "count": { "$sum": 1 }
    }},
    { "$match": { "count": { "$gt": 1 } } }
],{ "allowDiskUse": true}).forEach(function(doc) {
    doc.ids.sort().reverse();    // <-- this is the only real change
    doc.ids.shift();     // remove first match, which is now youngest
    bulk.find({ "_id": { "$in": doc.ids } }).remove();  // removes all $in list
    count++;

    // Execute 1 in 1000 and re-init
    if ( count % 1000 == 0 ) {
       bulk.execute();
       bulk = db.History.initializeOrderedBulkOp();
    }
});

if ( count % 1000 != 0 ) 
    bulk.execute();

使用特定字段

如果“确实”设置为添加另一个日期值来确定哪个是最年轻的,那么只需先在$push中添加数组,然后应用客户端排序功能。再一次只是一个非常简单的变化:

var bulk = db.History.initializeOrderedBulkOp(),
    count = 0;

// List "all" fields that make a document "unique" in the `_id`
// I am only listing some for example purposes to follow
db.History.aggregate([
    { "$group": {
        "_id": "$sessionId",
        "ids": { "$push": { 
            "_id": "$_id",
            "created": "$timeCreated"
        }},
        "count": { "$sum": 1 }
    }},
    { "$match": { "count": { "$gt": 1 } } }
],{ "allowDiskUse": true}).forEach(function(doc) {
    doc.ids = doc.ids.sort(function(a,b) {   // sort dates and just return _id
        return a.created.valueOf() < a.created.valueOf()
    }).map(function(el) { return el._id });
    doc.ids.shift();     // remove first match, which is now youngest
    bulk.find({ "_id": { "$in": doc.ids } }).remove();  // removes all $in list
    count++;

    // Execute 1 in 1000 and re-init
    if ( count % 1000 == 0 ) {
       bulk.execute();
       bulk = db.History.initializeOrderedBulkOp();
    }
});

if ( count % 1000 != 0 ) 
    bulk.execute();

所以这是一个非常简单的过程,对原始过程没有“真正的”改动,用于识别重复项,然后除去其中一个。

这里总是最好的方法让服务器完成查找重复项的工作,然后客户端在迭代游标时可以从返回的数组中找出哪个文档将被保存以及你要去哪些文档删除。

相关问题