看起来您应该能够使用以下内容添加其他字段(我忽略了匹配项):
db.test.aggregate(
{ $group: {
_id: { city_to: "$city_to" },
min: { $min: "$total_price" },
city_from: { $min: "$city_from" }
} }
);
但这不起作用。因为 $min 将在每个领域工作。举个例子:
> db.test.find();
{ "_id" : ObjectId("51156a11056d6f966f268f7f"), "city_from" : "LHR", "city_to" : "JFK", "total_price" : 500 }
{ "_id" : ObjectId("51156a1a056d6f966f268f80"), "city_from" : "LHR", "city_to" : "LGA", "total_price" : 400 }
{ "_id" : ObjectId("51156a1e056d6f966f268f81"), "city_from" : "DUB", "city_to" : "LGA", "total_price" : 400 }
{ "_id" : ObjectId("51156a27056d6f966f268f82"), "city_from" : "DUB", "city_to" : "JFK", "total_price" : 300 }
> db.test.aggregate( {$group: { _id: { city_to: "$city_to" }, min: { $min: "$total_price" }, city_from: { $min: "$city_from" } } } );
{
"result" : [
{
"_id" : {
"city_to" : "LGA"
},
"min" : 400,
"city_from" : "DUB"
},
{
"_id" : {
"city_to" : "JFK"
},
"min" : 300,
"city_from" : "DUB"
}
],
"ok" : 1
}
city_from : LHR完全消失了,尽管 LHR->LGA 和 DUB->LGA 的最低价格相同。city_from: { $min: "$city_from" }仅返回 [ DUB, LGA ] 的字符串最小值。当然,您可以拥有多个具有相同最低价格的文件(在这种情况下,LHR->LGA 和 DUB->LGA 均为 400)。
您必须分两步执行此操作:
> result = db.test.aggregate( {$group: { _id: { city_to: "$city_to" }, min: { $min: "$total_price" } } } );
> final = []
> result.result.forEach(function(entry) { final.push( { city_to: entry._id.city_to, min: entry.min, docs: db.test.aggregate( { $match: { city_to: entry._id.city_to, total_price: entry.min } } ).result } ) } );
然后给出结果:
> final
[
{
"city_to" : "LGA",
"min" : 400,
"docs" : [
{
"_id" : ObjectId("51156a1a056d6f966f268f80"),
"city_from" : "LHR",
"city_to" : "LGA",
"total_price" : 400
},
{
"_id" : ObjectId("51156a1e056d6f966f268f81"),
"city_from" : "DUB",
"city_to" : "LGA",
"total_price" : 400
}
]
},
{
"city_to" : "JFK",
"min" : 300,
"docs" : [
{
"_id" : ObjectId("51156a27056d6f966f268f82"),
"city_from" : "DUB",
"city_to" : "JFK",
"total_price" : 300
}
]
}
]