gpt4 book ai didi

mongodb - Mongo Aggregation 删除一个 id 的所有记录,只保留最旧的记录

转载 作者:行者123 更新时间:2023-12-04 21:28:26 24 4
gpt4 key购买 nike

有一个带有值的集合

_id:ObjectId('......')
ton_id :ObjectId('abcd')
value:587900
date:2019-12-13T07:09:40.075+00:00


_id:ObjectId('......')
ton_id :ObjectId('abcd')
value:50540
date:2018-1-13T07:09:40.075+00:00

_id:ObjectId('......')
ton_id :ObjectId('abcd1')
value:55400
date:2019-5-13T07:09:40.075+00:00


_id:ObjectId('......')
ton_id :ObjectId('abcd1')
value:22500
date:2018-12-13T07:09:40.075+00:00



对于 ton_ids abcdabcd1删除除最旧记录以外的所有记录。

所需的输出
_id:ObjectId('......')
ton_id :ObjectId('abcd')
value:50540
date:2018-1-13T07:09:40.075+00:00



_id:ObjectId('......')
ton_id :ObjectId('abcd1')
value:22500
date:2018-12-13T07:09:40.075+00:00

最佳答案

类似的东西应该工作。使用聚合选择要保留的 id,然后批量更新以删除其他 id。

var bulk = db.getCollection(colname).initializeUnorderedBulkOp();

db.getCollection(colname).aggregate([
{$match:{"ton_id":{"$in":[abcd, abcd1]}}},
{$sort:{"date":1}},
{$group:{
"_id":"$ton_id",
"keep_id":{"$first":"$_id"}
}},
{$project:{"_id":0, "ton_id":"$_id", "keep_id":1}}
]).forEach(function(doc){
bulk.find({"_id":{"$ne":doc.keep_id},"ton_id":doc.ton_id}).remove();
});
bulk.execute();

关于mongodb - Mongo Aggregation 删除一个 id 的所有记录,只保留最旧的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59678326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com