从汇总返回整个文档 [英] Return whole document from aggregation
问题描述
我正在使用以下查询为数据库中的每个帖子获取一条最新评论:
I'm using the following query to fetch one most recent comment for every post in database:
db.comments.aggregate([
{
"$match": {
"post_id": {
"$in": [ObjectId("52c5ce24dca32d32740c1435"), ObjectId("52c5ce24dca32d32740c15ad")]
}
}
},
{
"$sort": {"_id": -1}
},
{
"$group": {
"_id": "$post_id",
"lastComment": {
"$first": "$_id"
}
}
}
])
我希望它返回整个注释的文档,但它仅返回每个文档的_id
字段.那么,将所有最近的注释作为一个整体文档(或至少包括其他一些字段)的正确方法是什么?
I expect it to return the whole comment's document but it only returns the _id
field of each document. So what would be the proper way to get all most recent comments as a whole document (or at least include some other fields)?
推荐答案
当前,您无法通过单个$first
运算符来获取整个comment
文档.但是您可以在$group
步骤中包括其他必填字段(类似于_id
字段):
Currently you cannot get the whole comment
document via single $first
operator. But you can include other necessary fields (similar to _id
field) during $group
step:
{
"$group": {
_id: "$post_id",
lastComment: { "$first": "$_id" },
field_1: { "$first": "$field_1" },
field_2: { "$first": "$field_2" },
// ...
field_N: { "$first": "$field_N" }
}
}
根据此JIRA票证: https://jira.mongodb.org/browse/SERVER-5916 ,整个文档将可以从 2.5.3版本的汇总操作中返回.可以使用新变量:$$ROOT
或$$CURRENT
:
According to this JIRA ticket: https://jira.mongodb.org/browse/SERVER-5916, the whole document will be available to return from aggregation operations from 2.5.3 version. It will be possible using new variables: $$ROOT
or $$CURRENT
:
{
"$group": {
_id: "$post_id",
lastComment: { "$first": "$$CURRENT" }
}
}
这篇关于从汇总返回整个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!