Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在mongodb聚合管道中限制$group中的文档?_Mongodb - Fatal编程技术网

如何在mongodb聚合管道中限制$group中的文档?

如何在mongodb聚合管道中限制$group中的文档?,mongodb,Mongodb,假设在mongo db中有这些虚拟文档: { "_id" : ObjectId("58f24f38e5fe51fa52e3a90c"), "ref" : "r1", "ts" : 1492275000121 } { "_id" : ObjectId("58f24f54e5fe51fa52e3a90d"), "ref" : "r1", "ts" : 1492275028031 } { "_id" : ObjectId("58f24f5ce5fe51fa52e3a90e"

假设在mongo db中有这些虚拟文档:

{
  "_id" : ObjectId("58f24f38e5fe51fa52e3a90c"),
  "ref" : "r1",
  "ts" : 1492275000121
}
{
  "_id" : ObjectId("58f24f54e5fe51fa52e3a90d"),
  "ref" : "r1",
  "ts" : 1492275028031
}
{
  "_id" : ObjectId("58f24f5ce5fe51fa52e3a90e"),
  "ref" : "r2",
  "ts" : 1492275036560
}
{
  "_id" : ObjectId("58f24f62e5fe51fa52e3a90f"),
  "ref" : "r3",
  "ts" : 1492275042696
}
{
  "_id" : ObjectId("58f24f64e5fe51fa52e3a910"),
  "ref" : "r2",
  "ts" : 1492275044864
}
{
  "_id" : ObjectId("58f24f69e5fe51fa52e3a911"),
  "ref" : "r1",
  "ts" : 1492275049360
}
{
  "_id" : ObjectId("58f24f6be5fe51fa52e3a912"),
  "ref" : "r3",
  "ts" : 1492275051880
}
{
  "_id" : ObjectId("58f24f6ee5fe51fa52e3a913"),
  "ref" : "r3",
  "ts" : 1492275054512
}
{
  "_id" : ObjectId("58f24f70e5fe51fa52e3a914"),
  "ref" : "r2",
  "ts" : 1492275056344
}
我想要实现的是得到一个文档列表,每个ref都有一个最新的时间戳ts

比如:

获取ref位于[r1,r2]中的所有文档 按ref对这些文档进行分组 对于每组,根据ts返回最新文档 我期望:

[
    {
        "ref":"r1",
        "ts": 1492275049360
    },{
        "ref":"r2",
        "ts": 1492275056344
    }
]
我可以用一个db请求来完成吗?我查看了聚合函数,但找不到获取组的最新文档的方法。

您可以使用$sort by ts desc,后跟$group中的$first

db.collection.aggregate(
   [
     { $match: { ref: { $in: ["r1", "r2"] } } },
     { $sort: { ts: -1 } },
     { $group: { _id: "$ref", ts: { $first: "$ts" } } }
   ]
)