[英]How to limit documents in $group in mongodb aggregation pipeline?
假設在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
}
]
我可以用一個數據庫請求來做到這一點嗎? 我研究了聚合函數,但是找不到獲取組的最新文檔的方法。
您可以在ts
desc中使用$sort
,然后在$group
$first
。
db.collection.aggregate(
[
{ $match: { ref: { $in: ["r1", "r2"] } } },
{ $sort: { ts: -1 } },
{ $group: { _id: "$ref", ts: { $first: "$ts" } } }
]
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.