MongoDB 聚合错误返回错误结果

MongoDB Aggregation Error Returning wrong result

我有这样的 json 对象

{
    "_id": "5c2e811154855c0012308f00",
    "__pclass": "QXRzXFByb2plY3RcTW9kZWxcUHJvamVjdA==",
    "id": 44328,
    "name": "Test project via postman2//2",
    "address": "some random address",
    "area": null,
    "bidDate": null,
    "building": {
        "name": "Health Care Facilities",
        "type": "Dental Clinic"
    },
    "collaborators": [],
    "createdBy": {
        "user": {
            "id": 7662036,
            "name": "Someone Here"
        },
        "firm": {
            "id": 2520967,
            "type": "ATS"
        }
    },
    "createdDate": "2019-01-03T21:39:29Z",
    "customers": [],
    "doneBy": null,
    "file": null,
    "firm": {
        "id": 1,
        "name": "MyFirm"
    },
    "leadSource": {
        "name": "dontknow",
        "number": "93794497"
    },
    "location": {
        "id": null,
        "city": {
            "id": 567,
            "name": "Bahamas"
        },
        "country": {
            "id": 38,
            "name": "Canada"
        },
        "province": {
            "id": 7,
            "name": "British Columbia"
        }
    },
    "modifiedBy": null,
    "modifiedDate": null,
    "projectPhase": {
        "id": 1,
        "name": "pre-design"
    },
    "quotes": [{
        "id": 19,
        "opportunityValues": {
            "Key1": 100,
            "Key2 Key2": 100,
            "Key3 Key3 Key3": 200,
    }
    }],
    "specForecast": [],
    "specIds": [],
    "tags": [],
    "valuation": "something"
}

我正尝试在 MongoDB 中使用此查询进行聚合。我的聚合键是 4 级深并且还包含空格。在所有在线示例中,向我展示了第一级的聚合。查看在线代码,我尝试用我的第 4 级深键重新迭代相同的代码。

db.mydata.aggregate([
  {$match: {"id": 44328 } } ,
  {$group: { _id: "$quotes.id",
    totalKey2:{ $sum: "$quotes.opportunityValues.Key2 Key2"},
    totalKey3:{ $sum: "$quotes.opportunityValues.Key3 Key3 Key3"}
  }
  }
]);

这应该return

_id    totalKey2   totalKey3
 0 19    100         300

但是returning

_id    totalKey2   totalKey3
 0 19      0         0

我做错了什么?

虽然不建议在 Mongo 的字段名称中使用 space,但它可以按预期工作。

您的查询的问题是 "quotes" 是一个数组,您应该在分组之前先展开它。

这按预期工作:

db.mydata.aggregate([
  { $match: { "id": 44328 } } ,
  { $unwind: "$quotes" },
  { $group: { _id: "$quotes.id",
    totalKey2:{ $sum: "$quotes.opportunityValues.Key2 Key2" },
    totalKey3:{ $sum: "$quotes.opportunityValues.Key3 Key3 Key3" } }
  }
]);