相关疑难解决方法(0)

$ unwind empty array

我有一组用户,每个文档都有以下结构:

{
  "_id": "<id>",
  "login": "xxx",
  "solved": [
    {
      "problem": "<problemID>",
      "points": 10
    },
    ...
  ]
}
Run Code Online (Sandbox Code Playgroud)

该字段solved可能为空或包含任意多个子文档.我的目标是获得一个用户列表以及总分(总和points),其中尚未解决任何问题的用户将被分配总分为0.这是否可以通过单个查询执行此操作(理想情况下使用聚合框架)?

我试图在聚合框架中使用以下查询:

{ "$group": {
  "_id": "$_id",
  "login": { "$first": "$login" },
  "solved": { "$addToSet": { "points": 0 } }
} }
{ "$unwind": "$solved" }
{ "$group": {
  "_id": "$_id",
  "login": { "$first": "$login" },
  "solved": { "$sum": "$solved.points" }
} }
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

exception: The top-level _id field is the only field currently supported for exclusion
Run Code Online (Sandbox Code Playgroud)

先感谢您

mongodb aggregation-framework

22
推荐指数
2
解决办法
2万
查看次数

标签 统计

aggregation-framework ×1

mongodb ×1