MongoDB 在聚合查询中获取第一个和最后一个文档 [英] MongoDB get first and last document in aggregate query
问题描述
如何根据 time
字段获取第一个和最后一个文档.我可以使用 $group
并获取 $first
和 $last
文档,但我不需要在这里分组,只需获取第一个和最后一个完整文档.也许我可以使用 slice
?此查询不起作用:
How can I get first and last document based on time
field.
I can use $group
and get $first
and $last
document, but I don't need grouping here, just get first and last full document. Maybe I could use slice
? This query doesn't work:
{
"aggregate": "353469045637980_data",
"pipeline": [
{
"$match": {
"$and": [
{
"time": {
"$gte": 1461369600
}
},
{
"time": {
"$lt": 1461456000
}
}
]
}
},
{
"$project": {
"first": {
"$slice": 1
},
"last": {
"$slice": -1
}
}
}
]
}
推荐答案
好吧,您需要 $group
但您可以简单地使用一个常量(例如 null
,请参阅 id
从而导致单个组.$$ROOT 然后引用文档本身,您可以与 $first
和 $last
一起使用
Well you need $group
but you can simply use a constant (e.g. null
, see the docs) for its id
so that it results in a single group. $$ROOT then refers to the document itself which you can use with $first
and $last
like so
$group: {
_id: null,
first: { $first: "$$ROOT" },
last: { $last: "$$ROOT" }
}
当然你可以引入更多的 $project
阶段来将数据塑造成一个数组(正如你提到的你想要一个列表)等.
Of course you can introduce further $project
stages to shape that data into an array (as you mentioned you want a list) etc.
作为旁注,您可能需要引入 $sort
阶段以确保 $first
和 $last
具有正确的含义.
As a side note you may want to introduce a $sort
stage to make sure $first
and $last
have a proper meaning.
这篇关于MongoDB 在聚合查询中获取第一个和最后一个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!