wuh*_*ing 7 mongodb aggregation-framework
在聚合框架示例中,有第一个和最后一个示例:
db.zipcodes.aggregate( { $group:
{ _id: { state: "$state", city: "$city" },
pop: { $sum: "$pop" } } },
{ $sort: { pop: 1 } },
{ $group:
{ _id : "$_id.state",
biggestCity: { $last: "$_id.city" },
biggestPop: { $last: "$pop" },
smallestCity: { $first: "$_id.city" },
smallestPop: { $first: "$pop" } } }
Run Code Online (Sandbox Code Playgroud)
我可以获得完整的zipcodes文档$first吗?
编辑:
为了澄清,我在我的快递应用程序中使用coffeescript执行以下操作,看起来很愚蠢:
@aggregate(
{
$group :
_id : "$category"
cnt : { $sum : 1 }
id: {$first: "$_id"}
name: {$first: "$name"}
description: {$first: "$description"}
region: {$first: "$region"}
startedAt: {$first: "$startedAt"}
titleImage: {$first: "$titleImage"}
tags: {$first: "$tags"}
},
{$sort :{"createdAt" : -1}}
Run Code Online (Sandbox Code Playgroud)
字段(id,name,...标签)都是文档架构的字段.我只是想知道,有没有办法单独做到这一点$first.
小智 12
现在可以在2.6中使用,因为您可以使用$$ ROOT访问正在处理的文档.这样的事情应该有效:
@aggregate(
{
$group :
_id : "$category"
cnt : { $sum : 1 }
first: {$first : "$$ROOT"}
{$sort :{"createdAt" : -1}}
)
Run Code Online (Sandbox Code Playgroud)