我如何在mongodb中的正则表达式$ match中使用聚合中的字段? [英] How can I use a field from aggregate in a regex $match in mongodb?

查看:759
本文介绍了我如何在mongodb中的正则表达式$ match中使用聚合中的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

A very simplified version of my use case is to find all posts beginning with the authors name, something like this:

> 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"}
]);

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

So I want to identify all posts that start with the authors name. I'm trying with an aggregate like this, but I don't know how to extract the user's name from the aggregate pipeline to use in a regex match:

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

此处未定义名称,我需要提取名称来自管道上一步中的用户收集条目。出于某些原因,我不知道该怎么做。

The thing "name" here is not something defined, I need to extract the name from the users collection entry from the previous step of the pipeline. For some reason I don't understand how to do that.

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

This is probably super simple and I'm definitely feeling thick as a brick here… Any help highly appreciated!

推荐答案

您可以在 聚合 使用> $ 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"
  }}
])

这篇关于我如何在mongodb中的正则表达式$ match中使用聚合中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆