I have two collections, call
and contact
.
I want to join them and show the contact name in the call record. The below code is what I tried.
ps. when I change "d.v":"$mobile"
to "d.v":"some number"
it works, but when I use variable is not working, where is my problem ?
{
from: 'contact',
let: {"mobile":"$user"},
pipeline:[
{
"$project":{
d:{$objectToArray:"$data"},
doc:"$$ROOT",
}
},
{
"$unwind":{
path: "$d",
preserveNullAndEmptyArrays: true
}
},
{
"$match":{
"d.v":"$mobile"
}
},
],
as: 'name'
}
CodePudding user response:
As specified in the 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.
After changing these two to match the requirements your stage will look like this:
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"
}
}
])