按组计数删除MongoDB记录

3

我有很多包含重复地址的记录。基本上,我想删除那些重复地址数量大于50但小于300的记录。

这是我获取要删除的记录的方法:

db.directories.aggregate( [
   { $group: { _id: { address: "$address" }, total: { $sum: 1 } } },
   { $match: { total: { $gt: 50, $lt: 300 } } },
   { $sort: { total: -1 } }
], { allowDiskUse: true });
1个回答

2
您可以使用游标方法forEach()来迭代从aggregate()方法返回的游标,并使用remove()方法删除文档,例如以下示例:
var pipeline = [
   { $group: { _id: { address: "$address" }, total: { $sum: 1 } } },
   { $match: { total: { $gt: 50, $lt: 300 } } },
   { $sort: { total: -1 } }
];
var options = { allowDiskUse: true };
db.directories.aggregate(pipeline, options).forEach(function (doc){
    var query = {"address": doc._id.address};
    db.directories.remove(query);
});

我尝试过了,但它没有删除任何东西。它花了很长时间才完成,但文档仍然存在。 - Raza
1
@RazaFarooq 我的错,删除查询语句是错误的。应该是 {"address": doc._id} 而不是 {"address": doc._id.address},后者应该可以工作。让我知道结果如何。 - chridam
1
谢谢@chridam,我已经解决了。我应该注意到这个错误。 - Raza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接