首页 > 解决方案 > Mongoose 移除重复的社保客户

问题描述

我有customers重复的人SocialSecurity,我想删除它们并保留最新的客户。我通过比较_id并保留具有最大值的那个来做到这一点。不幸的是,当我使用愚蠢的数据时,我的代码似乎并不总是删除最小的_id. 知道为什么吗?我以为$sort会奏效

let hc = db.getSiblingDB('customer');
hc.customers.aggregate([
  {
      "$group": {
          _id: {socialsecurity: "$socialsecurity"},
          imeis: { $addToSet: "$_id" },
          count: { $sum : 1 }
      }
  },
  {
      "$match": {
          count: { "$gt": 1 }
      }
  },
  {
  $sort: {_id: 1}
  }

 ]).forEach(function(doc) {
    doc.socialsecurity.shift();
    hc.customers.remove({
        _id: {$in: doc.socialsecurity}
    });
 })

标签: mongodbmongoosemongodb-queryaggregation-framework

解决方案


问题

{ $sort: { _id: 1} }正在按升序排序

所以最小的将是_id数组中的第一个

doc.socialsecurity.shift();将从数组中删除最小的第一个元素。

解决方案

  1. { $sort: { _id: -1 } }降序排列

或者

  1. 更改doc.socialsecurity.shift();doc.socialsecurity.pop();从数组中删除最后一个元素。

推荐阅读