【发布时间】:2022-11-22 14:41:53
【问题描述】:
我在使用 MongoDB 聚合进行查询时遇到问题。
我有一个集合如下:
[
{
id: 1,
name: 'cash',
amount: 10,
},
{
id: 2,
name: 'IPT',
amount: 10,
terminal_type: 'inside',
card: {
id: 1,
name: 'visa',
},
},
{
id: 2,
name: 'IPT',
amount: 10,
terminal_type: 'outside',
card: {
id: 1,
name: 'visa',
},
},
]
预期结果:
[
{
id: 1,
name: 'cash',
amount: 10,
},
{
id: 2,
name: 'IPT',
amount: 20,
cards: [
{
id: 1,
name: 'visa',
amount: 20,
},
],
terminals: [
{
name: 'inside',
amount: 10,
},
{
name: 'outside',
amount: 10,
},
],
},
]
我试过的:
{
$group: {
_id: {
id: '$id',
card_id: '$card.id',
terminal_type: '$terminal_type',
},
name: {$first: '$name'},
amount: {$sum: '$amount'},
card_name: {$sum: '$card.name'},
}
},
{
$group: {
_id: {
id: '$id',
card_id: '$_id.card_id',
},
name: {$first: '$name'},
amount: {$sum: '$amount'},
card_name: {$first: '$card_name'},
terminals: {
$push: {
{ $cond: [
{$ifnull: ['$terminal_type', false]},
{
type: '$terminal_type',
amount: '$amount',
},
'$$REMOVE',
]
}
}
}
}
},
{
$group: {
_id: '$_id.id',
name: {$first: '$name'},
amount: {$sum: '$amount'},
cards: {
$push: {
{ $cond: [
{$ifnull: ['$id.card_id', false]},
{
id: '$_id.card_id',
name: '$card_name',
amount: '$amount',
},
'$$REMOVE',
],
},
},
terminals: // This is the problem where I can't figure out how get this value
}
}
我考虑在最后一组管道之前展开terminals,但我最终得到了重复的文档,这使得金额的总和不正确。任何人都可以帮助我解决这个问题或指出我可以在哪里阅读和了解更多相关信息吗?非常感谢。
【问题讨论】:
-
@nimrodserok 我已经在问题中提出了预期的结果
-
请注意,我的链接中的示例数据多了一份文件:
{ id: 2, name: "IPT", amount: 10, terminal_type: "outside", card: { id: 7, name: "visa" } } -
@nimrodserok 根据您链接中的数据,结果将是这样的:codeshare.io/786rYj
标签: mongodb aggregation-framework