首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不带allowDiskUse的mongodb数据库去重

不带allowDiskUse的mongodb数据库去重
EN

Stack Overflow用户
提问于 2021-01-05 00:55:34
回答 1查看 21关注 0票数 0

除了具有不同的_ids之外,我的集合中每个文档都有一个副本:

代码语言:javascript
复制
{ _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集群

有没有什么方法可以删除这些重复项,而不会在整个集合中运行长循环,这将花费很长的时间?

EN

回答 1

Stack Overflow用户

发布于 2021-01-25 20:01:03

我最近创建了一个代码来删除MongoDB中的重复文档,这应该是可行的:

代码语言:javascript
复制
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 });
  });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65566585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档