使用mongodb。我有一个车辆集合,每个车辆都有一系列的事故,每个事故都有一个日期。
Vehicle {
_id: ...,,
GasAMount...,
Type: ...,
Accidents: [
{
Date: ISODate(...),
Type: ..,
Cost: ..
},
{
Date: ISODate(..),
Type: ..,
Cost:...,
}
]
}如何在不使用聚合的情况下删除每辆车中最旧的事故?重要的是不要使用聚合方法。
发布于 2015-11-18 04:39:26
不幸的是,在这种情况下,您可能必须使用聚合,因为几乎不可能找到一个能够如此高效的非聚合解决方案。在这里,聚合对于获取具有最早日期的嵌入文档很有用。一旦你得到它们,更新就变得更容易了。下面演示了这个概念,使用MongoDB的来更新你的集合:
var bulk = db.vehicles.initializeUnorderedBulkOp(),
counter = 0,
pipeline = [
{ "$unwind": "$Accidents" },
{
"$group": {
"_id": "$_id",
"oldestDate": { "$min": "$Accidents.Date" }
}
}
];
var cur = db.vehicles.aggregate(pipeline);
cur.forEach(function (doc){
bulk.find({ "_id": doc._id }).updateOne({
"$pull": { "Accidents": { "Date": doc.oldestDate } }
});
counter++;
if (counter % 100 == 0) {
bulk.execute();
bulk = db.vehicles.initializeUnorderedBulkOp();
}
});
if (counter % 100 != 0) bulk.execute();https://stackoverflow.com/questions/33765736
复制相似问题