$unwind 空数组 [英] $unwind empty array
问题描述
我有一个用户集合,其中每个文档都具有以下结构:
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 及更新版本中,$unwind
运算符现在有一些选项,特别是 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
输出文档.如果为 false,$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 空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!