mongodb - 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}
});
})
解决方案
问题
{ $sort: { _id: 1} }
正在按升序排序
所以最小的将是_id
数组中的第一个
doc.socialsecurity.shift();
将从数组中删除最小的第一个元素。
解决方案
{ $sort: { _id: -1 } }
降序排列
或者
- 更改
doc.socialsecurity.shift();
以doc.socialsecurity.pop();
从数组中删除最后一个元素。
推荐阅读
- sharp-snmp - Snmp V3 缺少“不在时间窗口内”或“错误的引擎 ID”等异常
- javascript - javascript OOP无法读取构造函数它说未定义
- java - 无法使用 Spring Boot 找到 cfg.xml 资源 [hibernate.cfg.xml]
- python - 基于特殊字符过滤项目列表 - Python
- python - Pandas - 如何计算 groupby 对象的持续时间
- php - 推送器未在 laravel 的页面上显示通知
- python - 如何打印星星和数字序列?
- terraform - Terraform 嵌套动态块:不支持的块类型
- firebase - 如何收听添加到我的 Cloud Firestore 的新文档并将这些新数据附加到 BigQuery 表?
- python - subprocess.run("mv source destnation", shell=True) 给出输出没有这样的文件或目录,即使文件存在