let’s say I have 3 collections in MongoDB
"Col1": [
{
"accountCode": "xyz",
"ITSM": "SNOW",
"anotherFieldxxx": "x"
},
{
"accountCode": "abc",
"ITSM": "SNOW",
"anotherFieldxxx": "x"
}
],
"Col2": [
{
"accountCode": "xyz",
"manager": "John",
"anotherFieldyyy": "yyy"
},
{
"accountCode": "abc",
"manager": "Lisa",
"anotherFieldyyy": "yyy"
}
],
"Col3": [
{
"accountCode": "xyz",
"admin": "Peter",
"anotherFieldzzz": "z"
},
{
"accountCode": "abc",
"admin": "Mona",
"anotherFieldyyy": "yyy"
}
]
In the query I want to give only one value and it’s "ITSM" : "SNOW"
If there is many documents in Col1
with "ITSM" : "SNOW"
then I want to search for "accountCode"
in Col2
and get "manager"
value, then search for the same "accountCode"
in Col3
and get "admin"
value. Finally I want to get output like:
{"accountCode" : "xyz",
"ITSM" : "SNOW",
"manager" : "John",
"admin" : "Peter"},
{"accountCode" : "abc",
"ITSM" : "SNOW",
"manager" : "Paul",
"admin" : "Stephen"}
I tried with Aggregation but I am just beginner in MongoDb and finally I gave up.
Can you suggest what I should use to get my result?
—update
I have such query
db.Col1.aggregate([
{$project: {"anotherFieldxxx": 0}},
{$match: {"accountCode": "xyz"}},
{$lookup: {
from: "Col2",
localField: "accountCode",
foreignField: "accountCode",
as: "Col2"
}},
{ $unwind: "$Col2" },
{ $project: { "Col2.anotherFieldyyy" : 0 }},
{ $match: { "accountCode" : "xyz"}},
{
$lookup: {
from: "Col3",
localField: "accountCode",
foreignField: "accountCode",
as: "Col3"
}},
{$unwind: "$Col3"},
{$project: {"Col2.anotherFieldzzz": 0}}
])Pretty()
but what if there are also documents with "accountCode" : "abc"
in all collections?
2
Answers
Playground
One option is to
$match
documents with your wanted value and then use thereaccountCode
for$lookup
. No need to limit the search to one specificaccountCode
:See how it works on the playground example