问题描述
我有一个用户集合,其中每个文档都具有以下结构:
I have a collection of users where each document has following structure:
{
"_id": "<id>",
"login": "xxx",
"solved": [
{
"problem": "<problemID>",
"points": 10
},
...
]
}
字段solved
可以为空或包含任意多个子文档.我的目标是获取用户列表以及总得分(points
的总和),在该总得分中,尚未解决任何问题的用户将被分配总得分0.是否可以通过一个查询来做到这一点(理想情况下使用聚合框架)?
The field solved
may be empty or contain arbitrary many subdocuments. My goal is to get a list of users together with the total score (sum of points
) where users that haven't solved any problem yet will be assigned total score of 0. Is this possible to do this with a single query (ideally using aggregation framework)?
我试图在聚合框架中使用以下查询:
I was trying to use following query in aggregation framework:
{ "$group": {
"_id": "$_id",
"login": { "$first": "$login" },
"solved": { "$addToSet": { "points": 0 } }
} }
{ "$unwind": "$solved" }
{ "$group": {
"_id": "$_id",
"login": { "$first": "$login" },
"solved": { "$sum": "$solved.points" }
} }
但是我遇到以下错误:
exception: The top-level _id field is the only field currently supported for exclusion
提前谢谢
推荐答案
在MongoDB 3.2和更高版本中, 运算符现在具有一些选项,其中特别是preserveNullAndEmptyArrays
选项将解决此问题.
With MongoDB 3.2 version and newer, the $unwind
operator now has some options where in particular the preserveNullAndEmptyArrays
option will solve this.
如果此选项设置为true,并且路径为空,缺少或为空数组,则 输出文档.如果为假,则 $unwind
不会输出文档路径为空,缺少或为空数组.在您的情况下,将其设置为true:
If this option is set to true and if the path is null, missing, or an empty array, $unwind
outputs the document. If false, $unwind
does not output a document if the path is null, missing, or an empty array. In your case, set it to true:
db.collection.aggregate([
{ "$unwind": {
"path": "$solved",
"preserveNullAndEmptyArrays": true
} },
{ "$group": {
"_id": "$_id",
"login": { "$first": "$login" },
"solved": { "$sum": "$solved.points" }
} }
])
这篇关于$ unwind空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!