[英]Filter MongoDB collection using values from another collection
我是 MongoDB 初學者。 我有這些模式:
const postSchema = new mongoose.Schema(
{
content: { type: String, required: true, index: "text" },
author: { type: ObjectId, ref: "User", required: true, index: true }
}
);
const muteWordSchema = new mongoose.Schema({
word: { type: String, trim: true, required: true },
match: { type: String, enum: ["exact", "contains", "startsWith", "endsWith"], required: true },
});
我想做的是:
{ word: "test", match: "startsWith" }
將變成/(^|\s)test/g
,等等。如何使用聚合管道實現此目的?
我沒有得到答案,但無論如何我都會發布我找到的解決方案,因此它對其他遇到類似問題的人很有用。
db.posts.aggregate([
{
$lookup: {
from: "mutedwords",
pipeline: [
{
$project: {
_id: 0,
regEx: {
$switch: {
branches: [
{
case: {
$eq: [ "$match", "startsWith" ]
},
then: {
$concat: [
"\\W+",
"$word",
".*"
]
}
},
{
case: {
$eq: [ "$match", "endsWith" ]
},
then: {
$concat: [
"\w*",
"$word",
"(\\W+|$)"
]
}
},
{
case: {
$eq: [ "$match", "exact" ]
},
then: {
$concat: [
"\\W+",
"$word",
"(\\W+|$)"
]
}
}
],
default: "$word"
}
}
}
},
{
$group: {
_id: undefined,
result: {
$addToSet: "$regEx"
}
}
}
],
as: "mutedWords"
}
},
{
$addFields: {
mutedWords: {
$arrayElemAt: ["$mutedWords.result", 0]
}
}
},
{
$match: {
$expr: {
$eq: [
{
$filter: {
input: "$mutedWords",
cond: {
$regexMatch: {
input: "$content",
regex: "$$this",
options: "i"
}
}
}
},
[]
]
}
}
},
{
$unset: "mutedWords"
}
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.