我有两个集合,call
和 contact
。
我想加入他们并在通话记录中显示联系人姓名。下面的代码是我尝试过的。
ps。当我将 "d.v":"$mobile"
更改为 "d.v":"some number"
时它可以工作,但是当我使用变量时不起作用,我的问题在哪里?
{
from: 'contact',
let: {"mobile":"$user"},
pipeline:[
{
"$project":{
d:{$objectToArray:"$data"},
doc:"$$ROOT",
}
},
{
"$unwind":{
path: "$d",
preserveNullAndEmptyArrays: true
}
},
{
"$match":{
"d.v":"$mobile"
}
},
],
as: 'name'
}
最佳答案
如 docs 中所述:
To reference variables in pipeline stages, use the "$$" syntax.
...
A $match stage requires the use of an $expr operator to access the variables. The $expr operator allows the use of aggregation expressions inside of the $match syntax.
更改这两项以满足要求后,您的舞台将如下所示:
db.call.aggregate([
{
"$lookup": {
from: "contact",
let: {
"mobile": "$user"
},
pipeline: [
{
"$project": {
d: {
$objectToArray: "$data"
},
doc: "$$ROOT",
}
},
{
"$unwind": {
path: "$d",
preserveNullAndEmptyArrays: true
}
},
{
"$match": {
$expr: {
$eq: [
"$$mobile",
"$d.v"
]
}
}
},
],
as: "name"
}
}
])
关于mongodb - 查找聚合中的局部变量不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69243241/