如何在 mongodb 的正则表达式 $match 中使用聚合中的字段?

Vik*_*alk 5 mongodb aggregation-framework

我的用例的一个非常简化的版本是查找以作者姓名开头的所有帖子,如下所示:

\n\n
> db.users.find();\n{ "_id" : ObjectId("5c4185be19da7e815cb18f59"), "name" : "User1" }\n{ "_id" : ObjectId("5c4185be19da7e815cb18f5a"), "name" : "User2" }\n\ndb.posts.insert([\n  {author : ObjectId("5c4185be19da7e815cb18f59"), text: "User1 is my name"},\n  {author : ObjectId("5c4185be19da7e815cb18f5a"), text: "My name is User2, but this post doesn\'t start with it"}\n]);\n
Run Code Online (Sandbox Code Playgroud)\n\n

所以我想识别所有以作者姓名开头的帖子。我正在尝试使用这样的聚合,但我不知道如何从聚合管道中提取用户名以在正则表达式匹配中使用:

\n\n
db.users.aggregate([\n  {\n    $lookup: {\n      from: "posts",\n      localField: "_id",\n      foreignField: "author",\n      as: "post"\n    }\n  },\n  {\n    $match: { "post.text": { $regex: "^" + name}}\n  }\n]).pretty();\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

这里的“名称”不是定义的东西,我需要从管道上一步的用户集合条目中提取名称。由于某种原因,我不明白该怎么做。

\n\n

这可能非常简单,我在这里绝对感觉像块砖一样厚\xe2\x80\xa6 任何帮助都非常感谢!

\n

Ash*_*shh 1

您可以使用下面的aggregation方法$indexOfCP

db.users.aggregate([
  { "$lookup": {
    "from": "posts",
    "let": { "authorId": "$_id", "name": "$name" },
    "pipeline": [
      { "$match": {
        "$expr": {
          "$and": [
            { "$ne": [{ "$indexOfCP": ["$text", "$$name"] }, -1] },
            { "$eq": ["$author", "$$authorId"] }
          ]
        }
      }}
    ],
    "as": "post"
  }}
])
Run Code Online (Sandbox Code Playgroud)