给定称为sampledata的集合中的下列文档:
sampledata:
{
"link" : "demo-1",
"type" : "type-1",
"version" : 1,
"slug" : "slug-1",
"_id" : ObjectId("550acc38fd15150c290dd489")
}
{
"link" : "demo-2",
"type" : "type-2",
"version" : 1,
"slug" : "slug-2",
"_id" : ObjectId("550acc37fd15150c290dd46a")
}
{
"link" : "demo-3",
"type" : "type-3",
"version" : 1,
"slug" : "slug-3",
"_id" : ObjectId("550acc38fd15150c290dd46e")
}
{
"link" : "demo-3",
"type" : "type-3",
"version" : 2,
"slug" : "slug-3",
"_id" : ObjectId("550b6182dac1909834b7b38d")
}
{
"link" : "demo-3",
"type" : "type-3",
"version" : 3,
"slug" : "slug-3",
"_id" : ObjectId("550b61d3dac1909834b7b38e")
}我需要一个聚合管道,它返回每个“类型”文档的最后一个“版本”。因此,其结果应是:
{
"link" : "demo-1",
"type" : "type-1",
"version" : 1,
"slug" : "slug-1",
"_id" : ObjectId("550acc38fd15150c290dd489")
}
{
"link" : "demo-2",
"type" : "type-2",
"version" : 1,
"slug" : "slug-2",
"_id" : ObjectId("550acc37fd15150c290dd46a")
}
{
"link" : "demo-3",
"type" : "type-3",
"version" : 3,
"slug" : "slug-3",
"_id" : ObjectId("550b61d3dac1909834b7b38e")
}下面给出了我想要的大部分内容,但我很难返回所选文档中的其余字段,如下所示:
db.sampledata.aggregate([{"$group": { "_id": "$slug", lastVersion: {"$last":"$version"} } }])发布于 2015-03-20 02:23:21
$last运算符从提供的键在分组边界中的“最后”项中工作。通常,它与下面的$sort语句前面的$group语句一起使用。这种“命令”以所需的方式命令集合中的文档,以便“最后”获取预期的内容:
db.sampledata.aggregate([
{ "$sort": { "slug": 1, "version": 1 } },
{ "$group": {
"_id": "$slug",
"link": { "$last": "$link" },
"type": { "$last": "$type" },
"version": { "$last": "$version" },
"id": { "$last": "$_id" }
}}
])正如您所看到的,如果您想要按照“最后”的顺序匹配整个文档,则需要对每个字段使用操作符。要完全重建,您需要下面的$project
db.sampledata.aggregate([
{ "$sort": { "slug": 1, "version": 1 } },
{ "$group": {
"_id": "$slug",
"link": { "$last": "$link" },
"type": { "$last": "$type" },
"version": { "$last": "$version" },
"id": { "$last": "$_id" }
}},
{ "$project": {
"_id": "$id",
"slug": "$_id",
"link": 1,
"type": 1,
"version": 1
}}
])https://stackoverflow.com/questions/29158040
复制相似问题