【发布时间】:2021-09-23 08:56:03
【问题描述】:
我对 MongoDB 还很陌生,到目前为止进展顺利。但现在我正在尝试更深入地研究并使用聚合(),但有点被它弄糊涂了。
我有以下几点:
Link.aggregate([
{
$match: {
eclipseId: link.eclipseId,
},
},
{
$lookup: {
from: 'configitems',
localField: 'autotaskId',
foreignField: 'id',
as: 'autotask',
},
},
{
$lookup: {
from: 'companies',
localField: 'autotask.companyId',
foreignField: 'id',
as: 'company',
},
},
{
$lookup: {
from: 'billcharges',
localField: 'eclipseId',
foreignField: 'id',
as: 'eclipse',
},
},
{
$group: {
_id: '$eclipseId',
id: { $first: '$_id' },
company: { $first: { $arrayElemAt: ['$company', 0] } },
eclipse: { $first: { $arrayElemAt: ['$eclipse', 0] } },
autotask: { $first: { $arrayElemAt: ['$autotask', 0] } },
items: {
$push: '$$ROOT',
},
},
},
{
$lookup: {
from: 'subscriptions',
let: { materialCodeID: '$materialCodeID' },
pipeline: [
{ $match: { $expr: { $eq: ['$items.autotaskId', '$$materialCodeID'] } } },
],
as: 'subscription2',
},
},
{
$project: {
// company: 0,
items: {
company: 0,
eclipse: 0,
autotask: 0,
},
},
},
])
我有 3 个收藏:
- 配置项
- 公司
- 账单费用
$lookup 在这些工作上很好,但是我需要按eclipseId 分组并将所有匹配项推送到items 数组中。到目前为止,一切都很好。我面临的问题是,现在我可以说items 数组中的 4 个项目,我需要将每个项目添加到 subscriptions 集合中的 lookup 并保存到相关项目下的 subscription 键中
所以我想以以下格式结束:
{
"data": {
"_id": "4522",
"id": "60ec62cc5fe7a94738d30f6b",
"company": {
//some data
},
"eclipse": {
//some data
},
"autotask": {
//some data
},
"items": [
{
"_id": "60ec62cc5fe7a94738d30f6b",
"subscription": {
//some data
}
},
{
"_id": "60ec62cc5fe7a94738d30f6c",
"subscription": {
//some data
}
}
]
}
}
我尝试关注此SO Answer,但无济于事。 任何帮助将不胜感激
【问题讨论】:
标签: mongodb mongoose aggregation-framework