gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:47:38 27 4
gpt4 key购买 nike

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

> 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();

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

这可能非常简单,我绝对感觉这里很厚……非常感谢任何帮助!

最佳答案

您可以使用下面的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"
}}
])

关于mongodb - 如何在 mongodb 的正则表达式 $match 中使用来自聚合的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54249830/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com