My query goes like this im using aggregate function with lookup:
this.document.aggregate([
{
$lookup : {
from: "projects",
localField: "_id",
foreignField: "organization_id",
as: "projects",
},
},
{
$lookup : {
from: "accounts",
localField: "accounts",
foreignField: "_id",
as: "organization_accounts",
},
},
{
"$project": {
"_id" : false,
"id": "$_id",
"name": 1,
"email": "$email",
"projects.id": "$projects._id",
"projects.name" : 1,
"projects.organization_id" : 1,
"organization_accounts._id" : 1,
"organization_accounts.first_name" : 1,
"organization_accounts.last_name" : 1,
"organization_accounts.email" : 1,
"organization_accounts.main_org_id" : 1,
}
}
])
But the output goes like this:
"id": "5ec69acbc072871bb03dd773",
"email": "organization email",
"name": "Organization name",
"projects": [
{
"name": "project 1",
"organization_id": "5ec69acbc072871bb03dd773",
"id": [
"5ec6a08342ad5b0a28ba6876"
]
}
],
"organization_accounts": []
I've tried applying the solution from this question but it doesnt seem to work or idk.
The projects.id field should be a string not an array.
PS: Just new to mongoDB
You have to $unwind the embedded arrays. You will get the cartesian product of array length for each document. Example
this.document.aggregate([
{
$lookup : {
from: "projects",
localField: "_id",
foreignField: "organization_id",
as: "projects",
},
},
{
$lookup : {
from: "accounts",
localField: "accounts",
foreignField: "_id",
as: "organization_accounts",
},
},
{
"$project": {
"_id" : false,
"id": "$_id",
"name": 1,
"email": "$email",
"projects.id": "$projects._id",
"projects.name" : 1,
"projects.organization_id" : 1,
"organization_accounts._id" : 1,
"organization_accounts.first_name" : 1,
"organization_accounts.last_name" : 1,
"organization_accounts.email" : 1,
"organization_accounts.main_org_id" : 1,
}
},
{
$unwind: "$projects"
},
{
$unwind: "$projects.id"
}
])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.