[英]MongoDB aggregate accounting info
I am completely new to MongoDB aggregation. 我对MongoDB聚合完全陌生。 I currently, have a collection in which I save a few account names:
目前,我有一个集合,其中保存了一些帐户名:
accounts : _id: ObjectId; 帐户 :_id:ObjectId; name: String
名称:字符串
Example: Items: ObjectId(...) "Bank account" etc 示例:项目:ObjectId(...)“银行帐户”等
On top of that, I have a journal collection, in which I store accounting journal entries. 最重要的是,我有一个日记帐集合,其中存储了会计日记帐分录。 They look the following:
他们看起来如下:
journals : _id: ObjectId, debit: (Ref to accounts id), credit: (Ref to accounts id); 日记帐 :_id:对象编号;借方:(请参阅帐户ID);贷方:(请参阅帐户ID); amount
量
The idea is, that I save accounting entries like the following: Debit: (Id of "Bank Account"), Credit: (Id of "Share Capital") 这个想法是,我保存如下的会计条目:借方:(“银行帐户”的ID),贷方:(“股本”的ID)
Now, I am trying to use the aggregate get the total debit, total credit, and total sum (debit-credit) for all account types. 现在,我尝试使用汇总来获取所有帐户类型的总借方,总贷方和总金额(借方贷方)。
Now, I kind of this to work for only one specific account type: 现在,我将这种情况仅适用于一种特定的帐户类型:
db.journals.aggregate(
{ $project: {
_id: 0,
PosSentiment: {$cond: [{$eq: ['$debit', ObjectId("5a809cf86ce518470ec92502")]}, '$amount', 0]},
NegSentiment: {$cond: [{$eq: ['$credit', ObjectId("5a809cf86ce518470ec92502")]}, '$amount', 0]}
}},
{ $group: {
_id: 0,
debit: {$sum: '$PosSentiment'},
credit: {$sum: '$NegSentiment'}
}});
Unfortunately, this only gives me credit and debit for one type of account that I specific in the ObjectId, I don't have the total and I have to run this for every account. 不幸的是,这只能为我在ObjectId中指定的一种类型的帐户提供贷方和借方,我没有总计,我必须为每个帐户运行。
Is there a possibility to use aggregates to end up with a result like this [{_id: ..., name (from account collection), totaldebit, totalcredit, total}]? 是否有可能使用汇总来得出如下结果:[{_ id:...,名称(来自帐户收集),totaldebit,totalcredit,total}]?
Thank you very much! 非常感谢你!
You can use below aggregation. 您可以使用以下聚合。
db.journals.aggregate([
{"$lookup":{
"from":"accounts",
"localField":"debit",
"foreignField":"_id",
"as":"debit"
}},
{"$lookup":{
"from":"accounts",
"localField":"credit",
"foreignField":"_id",
"as":"credit"
}},
{"$project":{
"data":[
{name:"$debit","type":"debit"},
{name:"$credit","type":"credit"}
],
"amount":1
}},
{"$unwind":"$data"},
{"$group":{
"_id":{"account":{"$arrayElemAt":["$data.name",0]},"type":"$data.type"},
"total":{"$sum":"$amount"}
}},
{"$group":{
"_id":"$_id.account._id",
"name":{"$first":"$_id.account.name"},
"balances":{$push:{"type":"$_id.type","total":"$total"}},
"alltotal":{"$sum":"$total"}
}}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.