【发布时间】:2020-11-26 21:19:48
【问题描述】:
我有以下文件
loanRequest(只写我想投影的键)
{
"_id": "5f2bf26783f65d33026ea592",
"lendingpartner": {
/* some keys here */
},
"loans": [
{
"loanid": 43809,
"loanamount": 761256,
"jewels": [
"5f2bf26783f65d33026ea593",
"5f2bf26783f65d33026ea594"
"5f2bf26783f65d33026ea595"
],
}
]
}
质押珠宝
{
"_id": "5f2bf26783f65d33026ea593",
"netweight": 8.52,
"purity": 19,
}
我想要实现的是
{
"_id": "5f2bf2b583f65d33026ea603",
"lendingpartner": {
/* some keys here */
},
"loans": [
{
"loanid": 40010,
"loanamount": 100000,
"jewels": [
{
"_id": "5f2bf26783f65d33026ea593",
"netweight": 8.52,
"purity": 19,
},
{
"_id": "5f2bf26783f65d33026ea594",
"netweight": 5.2,
"purity": 40,
},
{
"_id": "5f2bf26783f65d33026ea595",
"netweight": 4.52,
"purity": 39,
}
]
}
]
}
由于我希望将珠宝详细信息填充到每笔贷款的珠宝数组中,$unwind 不会帮助我。 (我试过用它做实验)
我以为我可以在贷款数组上运行$map,然后为贷款的每个宝石运行$lookup(双地图?),但无法提出可行的解决方案。
无论如何,这似乎不是正确的方法。
这是我能想到的最好的结果(与我想要的结果相去甚远)。我正在使用地图有选择地从贷款对象中选择键。
const loanrequests = await db.collection('loanrequest').aggregate([
{ $match: { requester: ObjectID(user.id) } },
{
$project: {
lendingpartner: {
name: 1,
branchname: '$branch.branchname',
},
loans: {
$map: {
input: '$loans',
as: 'loan',
in: {
loanid: '$$loan.loanid',
loanamount: '$$loan.amount',
jewels: '$$loan.jewels',
},
},
},
},
},
/*
* I experimented with unwind here. Tried adding
* { $unwind: '$loans' },
* { $unwind: '$loans.jewels' }
* but it does not give me the result I need (as already said before)
*/
]).toArray();
我想,我需要在投影之前执行$lookup,但由于文档的 2 级嵌套结构(首先是 loans 数组,然后是 @987654331 @)
我今天开始使用 mongodb 聚合器,在寻找答案时,我偶然发现了类似的 Question,但它似乎更复杂,因此我更难理解。
谢谢!
【问题讨论】:
标签: node.js mongodb mongoose mongodb-query aggregation-framework