MongoDB聚集小组学生通过他们的当前课程,并获得具有宗教信仰的学生的总和=基督徒

发布于 2025-01-20 19:19:23 字数 974 浏览 1 评论 0原文

我有一些有关一些学生的信息。从这些数据中,我想通过他们的当前课程将学生分组,并获得宗教的总和= Christian

// Data

[{
    "indexNumber": 11111,
    "currentClass": "3C",
    "gender": "Female",
    "religon": "Christian",
  },
{
    "indexNumber": 22222,
    "currentClass": "3E",
    "gender": "Male",
    "religon": "Hindu",
  }

 ]

//聚合组(我目前完成的工作)

const stats = await Student.aggregate([
      {
        $group: {
          _id: '$currentClass',
          totalNumStudentsInSchool: { $sum: 1 },
          christianStudents: { $sum: { $religon: 'Christian' } },
        },
      },
    ]);

错误会出现。

christianStudents: { $sum: { $religon: 'Christian' } }

//当我添加此行时, 这样的输出

"stats": [
            {
                "_id": "3C",
                "christianStudents": 1
            },
            {
                "_id": "3E",
                "christianStudents": 0
            },
        ]

I have some information about some students. From this data I want to group students by their current class and get sum of students with the religion = Christian

//data

[{
    "indexNumber": 11111,
    "currentClass": "3C",
    "gender": "Female",
    "religon": "Christian",
  },
{
    "indexNumber": 22222,
    "currentClass": "3E",
    "gender": "Male",
    "religon": "Hindu",
  }

 ]

//Aggregation group (what I have currently done)

const stats = await Student.aggregate([
      {
        $group: {
          _id: '$currentClass',
          totalNumStudentsInSchool: { $sum: 1 },
          christianStudents: { $sum: { $religon: 'Christian' } },
        },
      },
    ]);

//Error is coming when I add this line

christianStudents: { $sum: { $religon: 'Christian' } }

//I want an output like this

"stats": [
            {
                "_id": "3C",
                "christianStudents": 1
            },
            {
                "_id": "3E",
                "christianStudents": 0
            },
        ]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

π浅易 2025-01-27 19:19:23

您可以将$ cond用于此类操作,请参见下面的代码

const stats = await Student.aggregate([
      {
        $group: {
          _id: '$currentClass',
          totalNumStudentsInSchool: { $sum: 1 },
          christianStudents: {$sum: {$cond: [ {$eq: [  "$religon", "Christian" ]} , 1 , 0 ]}},
        },
      },
    ]);

You can use $cond for such operations, see below code

const stats = await Student.aggregate([
      {
        $group: {
          _id: '$currentClass',
          totalNumStudentsInSchool: { $sum: 1 },
          christianStudents: {$sum: {$cond: [ {$eq: [  "$religon", "Christian" ]} , 1 , 0 ]}},
        },
      },
    ]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文