我在 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/