Answer a question

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!

Answers

You can use below aggregation using $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"
  }}
])
Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐