How to query for getting projected values from lookup pipeline as key pair in mongoose
{
$lookup:{
from:'response',
localField:'_id',
foreignField:'user',
as:'dataResponse'
pipeline:[{project:{ resId:1,status:1}]
}
email : "[email protected]"
dataRespose : [
{_id: '63515eea05c8c884a33b291d', resId: '632f2d8e470895396dccefdb', status: 'IN_PROGRESS'} ,
{_id: '6385ee9f451fa8879071bcde', resId: '63771adafa3b611596aaa15d', status: 'CREATED'}`]
how to get like this
email : "[email protected]"
dataRespose : {
632f2d8e470895396dccefdb : 'IN_PROGRESS' ,
63771adafa3b611596aaa15d : 'CREATED'
}
CodePudding user response:
One way that you can create an object using values for the field names is by using the $arrayToObject
operator. In the example below, we use that operator inside of a subsequent $addFields
stage and $map
over the dataResponse
array that is returned by the preceding $lookup
. During that processing we generate the object document with the k
and v
fields (needed for $arrayToObject
set to the values from the fields that you are interested in (resId
and status
):
{
"$addFields": {
"dataResponse": {
"$arrayToObject": {
"$map": {
"input": "$dataResponse",
"in": {
k: "$$this.resId",
v: "$$this.status"
}
}
}
}
}
}
Output:
[
{
"_id": 1,
"dataResponse": {
"632f2d8e470895396dccefdb": "IN_PROGRESS",
"63771adafa3b611596aaa15d": "CREATED"
},
"email": "[email protected]"
}
]
You could do something similar inside of the pipeline
embedded in the $lookup
if you desired, but functionally the results will be the same.