如何在mongodb中使用$lookup $let 变量?
How to use $lookup $let variables in mongodb?
尝试执行 lookup 并使用其中一个变量,但使用 $expr 会造成混淆。
我很确定 let 部分是正确的,但它说要在管道中使用它你需要一个 $expr,但我不明白在哪里或提供什么信息。
这是我目前的情况:
{"$lookup": {
"from": "likes",
"let": {'content': "$_id"},
"pipeline": [{'$match': { '$expr':
{user: mongoose.Types.ObjectId(req.user._id), content: mongoose.Types.ObjectId("$$content")}
}}],
"as": "liked"
}},
您只能使用 mongoose.Types.ObjectId
转换 req.user._id
,因为它成为聚合框架的常量值。要转换变量 $$content
,您必须使用 $toObjectId 运算符。
{"$lookup": {
"from": "likes",
"let": {'content': "$_id" },
"pipeline": [
{'$match': { $expr: { $and: [
{ $eq: [ "$user", mongoose.Types.ObjectId(req.user._id) ] },
{ $eq: [ "$content", { $toObjectId: "$$content" } ] },
] } } }
],
"as": "liked"
}},
尝试执行 lookup 并使用其中一个变量,但使用 $expr 会造成混淆。
我很确定 let 部分是正确的,但它说要在管道中使用它你需要一个 $expr,但我不明白在哪里或提供什么信息。
这是我目前的情况:
{"$lookup": {
"from": "likes",
"let": {'content': "$_id"},
"pipeline": [{'$match': { '$expr':
{user: mongoose.Types.ObjectId(req.user._id), content: mongoose.Types.ObjectId("$$content")}
}}],
"as": "liked"
}},
您只能使用 mongoose.Types.ObjectId
转换 req.user._id
,因为它成为聚合框架的常量值。要转换变量 $$content
,您必须使用 $toObjectId 运算符。
{"$lookup": {
"from": "likes",
"let": {'content': "$_id" },
"pipeline": [
{'$match': { $expr: { $and: [
{ $eq: [ "$user", mongoose.Types.ObjectId(req.user._id) ] },
{ $eq: [ "$content", { $toObjectId: "$$content" } ] },
] } } }
],
"as": "liked"
}},