Mongodb:$group 的 _id 中的嵌套字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12878722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongodb: nested field in $group's _id
提问by airportyh
Assume we have documents like this in the collection
假设我们在集合中有这样的文档
{
_id: {
element_id: '12345',
name: 'foobar'
},
value: {
count: 1
}
}
I am using the aggregation framework to do a $group, like so
我正在使用聚合框架来做一个$group,像这样
db.collection.aggregate([
{ $group: { _id: '$_id.element_id', total: { $sum: '$value.count' } } }
])
And got a result of
并得到了结果
{ "result" : [ { "_id" : null, "total" : 1 } ], "ok" : 1 }
Notice that the _idfield in the result is null.From experimentation it seems that $group is not allowing a nested field declaration for its _id(e.g. $_id.element_id).
请注意,_id结果中的字段为空。从实验来看,似乎 $group 不允许对其_id(例如$_id.element_id)进行嵌套字段声明。
Why is this? And is there a workaround for it?
为什么是这样?是否有解决方法?
Thank you.
谢谢你。
回答by airportyh
I found a workaround using $project.
我找到了一种解决方法,使用$project.
db.collection.aggregate([
{ $project: { element_id: '$_id.element_id', count: '$value.count' } },
{ $group: { _id: '$element_id', total: { $sum: '$count' } } }
])
$project Reshapes a document stream by renaming, adding, or removing fields.
$project 通过重命名、添加或删除字段来重塑文档流。
http://docs.mongodb.org/manual/reference/aggregation/#_S_project
http://docs.mongodb.org/manual/reference/aggregation/#_S_project
回答by cacsar
This turns out to have been issue SERVER-7491. It appears to have been fixed in 2.2.2 (released about 3 days ago).
结果证明这是问题SERVER-7491。它似乎已在 2.2.2(大约 3 天前发布)中修复。
The workaround mentioned above worked well for me in 2.2.1. As a note, when using the $project workaround (pre 2.2.2) excluding _id from the $project with _id:0 is inadvisable as it appears to behave quite strangely, I ended up with some working properly and some where that portion of the _id field was missing in the end result within the same aggregation.
上面提到的解决方法在 2.2.1 中对我来说效果很好。需要注意的是,当使用 $project 解决方法(2.2.2 之前的版本)从 $project 中排除 _id 和 _id:0 是不可取的,因为它的行为似乎很奇怪,我最终得到了一些正常工作和一些_id 字段在同一聚合中的最终结果中丢失。

