如何消除重复项但在 MongoDB 中保留包含更多字段的文档

how to eliminate duplicates but keep the document with more fields in MongoDB

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

enter image description here

我需要保留具有较大字段的文档并删除其他重复项。

最后我不得不使用 highDate 字段作为过滤器才能删除记录。 仅保留具有最旧“highDate”字段的记录。

 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(); 
}