我有一个集合,其中的条目看起来像这样:
{"placeId" : "0b980482-ab4b-4685-95ab-ecc2dcba1837","placeName" : "B8 Göteborg","created" : ISODate("2017-04-09T14:53:01.005Z"),"debitAccount" : "1581","debitAmount" : 26.0,"creditAccount" : "3013","creditAmount" : 23.2142791748047,"taxAccount" : "2620","taxAmount" : 2.78572010993958},
{"placeId" : "0b980482-ab4b-4685-95ab-ecc2dcba1837","placeName" : "B8 Göteborg","created" : ISODate("2017-04-09T14:53:01.005Z"),"debitAccount" : "1581","debitAmount" : 26.0,"creditAccount" : "3014","creditAmount" : 53.2142791748047,"taxAccount" : "2621","taxAmount" : 5.78572010993958}
我希望输出的结果是这样的:
我想要的输出结果类似于:
{
"_id" : "B8 - Göteborg",
"days" : [
{
"date" : "2017-03-24",
"creditAccounts" : [
{
"creditAccount" : "3013",
"creditAccountSum" : 23.214279174804
},
{
"creditAccount" : "3014",
"creditAccountSum" : 53.2142791748047,
},
],
"debitAccounts" : [
{
"debitAccount" : "1581",
"debitAccountSum" : 52
}
],
"taxAccounts" : [
{
"taxAccount" : "2620",
"taxAccountSum" : 2.78572010993958
},
{
"taxAccount" : "2621",
"taxAccountSum" : 5.78572010993958
}
]
}
]
}
根据地点和日期,列出所有唯一的信用账户、借记账户、税收账户及其总和。我已经成功对其中一个字段进行了分组,看起来像这样:
db.getCollection('accounting_records').aggregate([
{$match : {...},
{$group: {_id: {placeName :'$placeName',year: {$substr: ['$created',0,4]},month: {$substr: ['$created',5,2]},dayOfMonth: {$substr: ['$created',8,2]},creditAccount:'$creditAccount'}, created: {$max: '$created'},records: { $addToSet: "$$ROOT" }}},
{$sort : {created : 1}},
{$group: {_id: {placeName :'$_id.placeName',year: '$_id.year',month: '$_id.month',dayOfMonth: '$_id.dayOfMonth'},created: {$max: '$created'}, creditAccounts:{$push :{creditAccount: '$_id.creditAccount',sum : {$sum: '$records.creditAmount'}, creditAccountName:'$records.creditAccountName'}}}},
{$sort : {created : 1}},
{$group : {_id : '$_id.placeName', created: {$max: '$created'}, days : {$push: {date: {$concat: ['$_id.year','-','$_id.month','-','$_id.dayOfMonth']},creditAccounts : '$creditAccounts'}}}},
{$sort : {_id : 1}},
])
但我不知道如何对所有的信用账户、税务账户和借记账户进行分组管理。也许可以使用MapReduce来实现,但是由于阅读到性能比使用聚合框架要差得多,因此尚未深入研究。