除了具有不同的_ids之外,我的集合中每个文档都有一个副本:
{ _id: ObjectId("5ff22dcd3c8ce5f425c08a6d"),
model: '1r9',
path: 'path1.png',
xmax: 460,
xmin: 395,
ymax: 464,
ymin: 406 }
{ _id: ObjectId("5ff42dcd7c8ce5f425c08a70"),
model: '1r9',
path: 'path1.png',
xmax: 460,
xmin: 395,
ymax: 464,
ymin: 406 }我在这里尝试了很多解决方案:Fastest way to remove duplicate documents in mongodb
但是,我使用的是不支持allowDiskUse: true的MongoDB Atlas集群
有没有什么方法可以删除这些重复项,而不会在整个集合中运行长循环,这将花费很长的时间?
发布于 2021-01-25 20:01:03
我最近创建了一个代码来删除MongoDB中的重复文档,这应该是可行的:
const query = [
{
$group: {
_id: {
model: "$model",
},
dups: {
$addToSet: "$_id",
},
count: {
$sum: 1,
},
},
},
{
$match: {
count: {
$gt: 1,
},
},
},
];
const cursor = collection.aggregate(query).cursor({ batchSize: 10 }).exec();
cursor.eachAsync((doc, i) => {
doc.dups.shift(); // First element skipped for deleting
doc.dups.map(async (dupId) => {
await collection.findByIdAndDelete({ _id: dupId });
});
});https://stackoverflow.com/questions/65566585
复制相似问题