在MongoDB中聚集嵌套文档的总和

k7fdbhmy  于 2023-03-07  发布在  Go
关注(0)|答案(1)|浏览(118)

我正在使用MongoDB创建一个投票应用程序。当在MongoDB中运行getAllPersons查询时,我试图检索每个数据库人的所有“选票”(即选票.评级)的总和-但无法使其工作。
下面是getAllPersons查询的输出示例

[   
    {
        "_id": "63964b3f9677c609e9c81054",
        "name": "Gordie Howe",
        "img": "./assets/gordie-howe.png",
        "votes": [
            {
                "rating": 1,
                "_id": "63c08fb8f8640bf8bb683314",
                "ratingId": "63c08fb8f8640bf8bb683315",
                "createdAt": "2023-01-12T22:54:48.659Z"
            },
            {
                "rating": 1,
                "_id": "63c08fccf8640bf8bb68334e",
                "ratingId": "63c08fccf8640bf8bb68334f",
                "createdAt": "2023-01-12T22:55:08.455Z"
            },
            {
                "rating": 1,
                "_id": "63c14d5ec2101f2f38ddf941",
                "ratingId": "63c14d5ec2101f2f38ddf942",
                "createdAt": "2023-01-13T12:23:58.692Z"
            }
                       ]
},
{
        "_id": "63964b3f9677c609e9c81059",
        "name": "Gordon",
        "img": "./assets/gordon.png",
        "votes": [
            {
                "_id": "63c08099b1489ae00cbc00a6",
                "ratingId": "63c08099b1489ae00cbc00a7",
                "createdAt": "2023-01-12T21:50:17.684Z"
            },
            {
                "_id": "63c080a0b1489ae00cbc00aa",
                "ratingId": "63c080a0b1489ae00cbc00ab",
                "createdAt": "2023-01-12T21:50:24.301Z"
            },
]
}

我想在数据库中汇总每个人的投票总数。
下面是我的controllers.js文件中的内容:

getAllPersons(req, res) {
    Person.aggregate(
//here is my attempt at aggregating the votes per person 
      [
        { $unwind: "$votes" },
        {
          $group: {
            _id: null,
            vote_sum: { $sum: "$votes.rating" },
          },
        },
      ],
      (err, result) => {
        if (err) {
          res.status(500).send(err);
        } else {
          res.status(200).send(result);
        }
      }
    );
  },

在Insomnia中测试路由时,我收到以下错误:“确定”:0,“代码”:40324,“代码名称”:“位置40324”

llmtgqce

llmtgqce1#

如果您的数据已经按个人进行了聚合,那么您只需对votes.rating字段求和。

db.collection.aggregate([
  {
    $set: {
      vote_sum: {
        $sum: "$votes.rating"
      }
    }
  }
])

Demo

相关问题