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

时间:2019-01-18 08:04:13

标签: mongodb aggregation-framework

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

> db.users.find();
{ "_id" : ObjectId("5c4185be19da7e815cb18f59"), "name" : "User1" }
{ "_id" : ObjectId("5c4185be19da7e815cb18f5a"), "name" : "User2" }

db.posts.insert([
  {author : ObjectId("5c4185be19da7e815cb18f59"), text: "User1 is my name"},
  {author : ObjectId("5c4185be19da7e815cb18f5a"), text: "My name is User2, but this post doesn't start with it"}
]);

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

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

这里的“名称”一词没有定义,我需要从管道的上一步的用户集合条目中提取名称。由于某些原因,我不知道该怎么做。

这可能是非常简单的,在这里,我肯定感觉像砖头一样厚……任何帮助,我们将不胜感激!

1 个答案:

答案 0 :(得分: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"
  }}
])