假设我在MongoDB中有3个集合
"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"
}
]
在查询中,我只想给予一个值,它是"ITSM" : "SNOW"
如果在Col1
中有很多文档带有"ITSM" : "SNOW"
,那么我想在Col2
中搜索"accountCode"
并得到"manager"
值,然后在Col3
中搜索相同的"accountCode"
并得到"admin"
值。最后我想得到这样的输出:
{"accountCode" : "xyz",
"ITSM" : "SNOW",
"manager" : "John",
"admin" : "Peter"},
{"accountCode" : "abc",
"ITSM" : "SNOW",
"manager" : "Paul",
"admin" : "Stephen"}
我尝试了聚合,但我只是MongoDb的初学者,最后我放弃了。你能建议我应该用什么来得到我的结果吗?
---更新
我有这样的疑问
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()
但是如果所有集合中也有"accountCode" : "abc"
的文档呢?
2条答案
按热度按时间bvjxkvbb1#
一个选项是
$match
文档与您想要的值,然后使用那里accountCode
为$lookup
。没有必要限制搜索到一个特定的accountCode
:了解它在playground example上的工作原理
qacovj5a2#
Playground