mongodb - 在 mongodb 中删除重复文档的最快方法

我在 mongodb 中有大约 170 万个文档(将来会超过 1000 万个)。其中一些代表我不想要的重复条目。文档的结构是这样的:

{
    _id: 14124412,
    nodes: [
        12345,
        54321
        ],
    name: "Some beauty"
}

如果文档与另一个具有同名的文档至少有一个节点相同,则该文档是重复的。删除重复项最快的方法是什么?

最佳答案

dropDups: true 选项在 3.0 中不可用。

我有一个带有聚合框架的解决方案,用于收集重复项,然后一次性删除。

它可能比系统级别的“索引”更改要慢一些。但最好考虑一下您要删除重复文档的方式。

一个。一次性删除所有文件

var duplicates = [];

db.collectionName.aggregate([
  { $match: { 
    name: { "$ne": '' }  // discard selection criteria
  }},
  { $group: { 
    _id: { name: "$name"}, // can be grouped on multiple properties 
    dups: { "$addToSet": "$_id" }, 
    count: { "$sum": 1 } 
  }},
  { $match: { 
    count: { "$gt": 1 }    // Duplicates considered as count greater than one
  }}
],
{allowDiskUse: true}       // For faster processing if set is larger
)               // You can display result until this and check duplicates 
.forEach(function(doc) {
    doc.dups.shift();      // First element skipped for deleting
    doc.dups.forEach( function(dupId){ 
        duplicates.push(dupId);   // Getting all duplicate ids
        }
    )
})

// If you want to Check all "_id" which you are deleting else print statement not needed
printjson(duplicates);     

// Remove all duplicates in one go    
db.collectionName.remove({_id:{$in:duplicates}})  

b.您可以一个一个地删除文档。

db.collectionName.aggregate([
  // discard selection criteria, You can remove "$match" section if you want
  { $match: { 
    source_references.key: { "$ne": '' }  
  }},
  { $group: { 
    _id: { source_references.key: "$source_references.key"}, // can be grouped on multiple properties 
    dups: { "$addToSet": "$_id" }, 
    count: { "$sum": 1 } 
  }}, 
  { $match: { 
    count: { "$gt": 1 }    // Duplicates considered as count greater than one
  }}
],
{allowDiskUse: true}       // For faster processing if set is larger
)               // You can display result until this and check duplicates 
.forEach(function(doc) {
    doc.dups.shift();      // First element skipped for deleting
    db.collectionName.remove({_id : {$in: doc.dups }});  // Delete remaining duplicates
})

https://stackoverflow.com/questions/14184099/

相关文章:

mongodb - 使用 Mongo 集合中的特殊字符

c# - Mongodb -- 使用 c# 驱动程序包含或排除某些元素

mongodb - Spring数据MongoDb : MappingMongoConverter

javascript - 如果 .find() mongoose 没有找到任何东西,请执行某些操作

mongodb - 为什么不用mongodb?

python - 如何将 MongoDB 查询转换为 JSON?

python - pymongo-如何为字段以及其他查询参数设置不同的值

mongodb - 使用 $toLower 更新 MongoDB 集合

mongodb - 使用mongodb在UTC中存储日期时如何处理时区问题?

javascript - 如何在 MongoDB 中查询引用的对象?