作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我的用例的一个非常简化的版本是查找所有以作者姓名开头的帖子,如下所示:
> 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/
我是一名优秀的程序员,十分优秀!