首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在MongoDB中消除重复并保留多个字段的文档

问如何在MongoDB中消除重复并保留多个字段的文档
EN

Stack Overflow用户
提问于 2020-08-08 05:43:52
回答 1查看 31关注 0票数 0

我有以下查询:我有重复的文档,但我需要删除它们,但保留mongodb中具有最大字段的文档。重复的字段是"financialAccount“我设法进行了查询,但在某些情况下,它会删除我不想要的文档。你能帮我拿一下这个吗?谢谢。

enter image description here

我需要保留包含较大字段的文档,并删除其他重复的字段。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-11 08:09:29

最后,我不得不使用highDate字段作为过滤器来删除记录。只保留具有最旧的"highDate“字段的记录。

代码语言:javascript
复制
 bulk  = db.financialAccount.initializeUnorderedBulkOp();
count = 0;
db.financialAccount.aggregate([
    { '$sort': { 'createDate': 1 }}, 
    {  $match : { financialAccount: {"$in":[
        '548541000'
     ]}}},
    { '$group': { '_id': '$financialAccount', 'ids': { '$push': '$_id' }, 'count': { '$sum': 1 },'financialAccount':{'$first': "$financialAccount"}}}, 
    { '$match': { 'count': { '$gt': 1 }}}
]).forEach(function(doc) {
    doc.ids.shift();
    bulk.find({'_id': { '$in': doc.ids }}).remove(); 
    count++; 
    if(count === 100) { 
        bulk.execute(); 
        bulk = db.financialAccount.initializeUnorderedBulkOp();
    }
})

if(count !== 0) { 
    bulk.execute(); 
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63309499

复制
相关文章

相似问题

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