Вы можете просто достичь этого, используя $lookup
и $project
агрегации
Если у вас версия mongodb 3.6 и выше
db.users.aggregate([
{ "$lookup": {
"from": Organisation.collection.name,
"let": { "emaildid": "$emaildid" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$emaildid", "$$emaildid" ] } } }
],
"as": "organisation"
}},
{ "$unwind": "$organisation" },
{ "$project": {
{ "id": 1, "name": 1, "emailid": 1, "org": "$organisation.org1" }
}}
])
Если у вас версия mongodb 3.4 и ниже
db.users.aggregate([
{ "$lookup": {
"from": Organisation.collection.name,
"localField": "emaildid",
"foreignField": "emaildid",
"as": "organisation"
}},
{ "$unwind": "$organisation" },
{ "$project": {
{ "id": 1, "name": 1, "emailid": 1, "org": "$organisation.org1" }
}}
])
попробуйте также $replaceRoot
db.Organisation.aggregate([
{ "$match": { "name": "org1" }},
{ "$lookup": {
"from": Organisation.collection.name,
"let": { "emailAddress": "$emailAddress", "name": "$name" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$emailAddress", "$$emailAddress" ] } } },
{ "$addFields": { "orgName": "$$name" }}
],
"as": "users"
}},
{ "$unwind": "$users" },
{ "$replaceRoot": { "newRoot": "$users" } }
])