为什么 $lookup 中的 $regex 通过 $addFields 结果在 mongodb 聚合中不起作用?

问题描述 投票:0回答:1

我有

groups
students
收藏。

Groups: {_id : ObjectId, title: String}
Students{mainGroups: String}

mainGroups
是一个连接字符串,对于所有
groups
,每个学生都在学校学习过。

我的代码给了我所有

students
的所有
groups
集合。

我想将

groups
集合与
students
聚合,并将
students
集合作为单个数组,对于每个
groups
,无论返回多少个
students

[
  //mainGroups is String that`s why I convert Group`s $_id to String here
  {$addFields: {
    gid: {$toString:"$_id"}  
  }},
  {$project: {
     _id: 1,
     gid: 1,
     title:1
  }},
  { 
   $lookup: {
    "from": 'students',
    "let": {"groupId": "$gid"},
    pipeline: [
      {"$match": 
        {"$expr" :  
          {"mainGroups":{"$regex": "$$groupId", "$options" :"i"}}
        }
      }
    ],
    as: "student"
   }
  },
]

如何获取每个

students
groups
的数量?

node.js mongodb mongodb-query aggregation-framework
1个回答
0
投票

像这样修改你的代码:

[
    {
        $addFields: {
            gid: { $toString: "$_id" }
        }
    },
    {
        $lookup: {
            from: 'students',
            let: { groupId: "$gid" },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $regexMatch: {
                                input: "$mainGroups",
                                regex: { $concat: [".*", "$$groupId", ".*"] },
                                options: "i"
                            }
                        }
                    }
                }
            ],
            as: "students"
        }
    },
    {
        $project: {
            _id: 1,
            gid: 1,
            title: 1,
            studentCount: { $size: "$students" }
        }
    }
]

让我解释一下我们所做的更改以及原因:

  • 我们没有在

    $match
    阶段的
    $lookup
    表达式中使用 $regex 运算符,而是选择了
    $regexMatch
    运算符。此更改允许我们在字符串中搜索特定模式。

  • 为了动态构造正则表达式模式,我们现在使用基于

    $$groupId
    变量的 $concat。

  • $project
    阶段,我们使用
    $size
    运算符来确定在
    $lookup
    阶段填充的学生数组中的学生数量。

因此,最终输出中的每个小组文档将包含一个名为 StudentCount 的新字段,指示与该小组关联的学生总数,由 mainGroups 字段确定。

© www.soinside.com 2019 - 2024. All rights reserved.