可以使用以下语句删除Mongo数据库中的重复数据:

db.collection.aggregate([
  // group by fields to find duplicates
  {
    $group: {
      _id: {field1: "$field1", field2: "$field2", field3: "$field3"},
      uniqueIds: {$addToSet: "$_id"},
      count: {$sum: 1}
    }
  },
  // filter groups with count greater than 1 (i.e. duplicates)
  {
    $match: {
      count: {$gt: 1}
    }
  },
  // delete duplicate documents
  {
    $project: {
      _id: 0,
      deleteIds: {$slice: ["$uniqueIds", 1, {$subtract: [{$size: "$uniqueIds"}, 1]}]}
    }
  },
  {
    $unwind: "$deleteIds"
  },
  {
    $replaceRoot: {newRoot: "$deleteIds"}
  }
]).forEach(function(doc) {
   db.collection.deleteOne({_id: doc._id});
});

这个语句使用了聚合管道,在数据库中查找重复数据并删除它们。请注意,它假定您已经在Mongo shell中打开了数据库,并且需要将 db.collection 替换为您要操作的实际集合名称

mongo删除重复数据语句

原文地址: https://www.cveoy.top/t/topic/fg3F 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录