简体   繁体   English

MongoDB 如何计算子文档总数大于3且子文档值之和大于15000

[英]MongoDB How to count where total of sub documents is greater than 3 and sum of sub documents value is greater than 15000

Sample data:样本数据:

{
        "_id" : "5e7b0e1c4669fe48ea07b63a",
        "isActive" : false,
        "balance" : -1503.89,
        "age" : 27,
        "eyeColor" : "green",
        "name" : "Allison Alvarez",
        "gender" : "female",
        "company" : "RONELON",
        "email" : "allisonalvarez@ronelon.com",
        "phone" : "+1 (963) 559-2276",
        "address" : "583 Sumpter Street, Stewartville, West Virginia, 110",
        "registered" : "2016-10-19T11:45:39 -01:00",
        "outstandingloans" : [
                {
                        "id" : 0,
                        "balance" : -710.65
                },
                {
                        "id" : 1,
                        "balance" : -2979.51
                },
                {
                        "id" : 2,
                        "balance" : -2520.79
                },
                {
                        "id" : 3,
                        "balance" : -3488.78
                }
        ]
}

I'm trying to find the count of males who have more than 3 outstanding loans with total sum of balances less than -15000.我正在尝试查找拥有超过 3 笔未偿贷款且余额总和小于 -15000 的男性人数。

What I´ve got working so far is:到目前为止我的工作是:

db.defaulters.aggregate([
    {$match: { "gender" : "male"}},
    {$project: {_id: "$name", loansGrt3: {$gte: [{$size: '$outstandingloans'}, 3]} }}
]);

And

db.defaulters.find( 
{ $where: "this.outstandingloans.length > 3"}
).count();
db.defaulters.aggregate([
  { $unwind: "$outstandingloans" },
  { $project: 
       { _id:1, 
         size_of_outstandingloans: { $size: "$outstandingloans"},
         totalBalance: { $sum: "$outstandingloans.amount" }
       }         
  },
  { $match: { $and: [ {"size_of_outstandingloans": {$gt: 3} },  {"totalBalance": {$lt: -15000} }] }}
])

This gave me the answer I was looking for in case it helps anyone.. Not sure it's exactly correct but it gave me the correct results.这给了我正在寻找的答案,以防它对任何人有帮助。不确定它是否完全正确,但它给了我正确的结果。

db.defaulters.aggregate( [
    {$match: { gender : "male"}},
    { $unwind: "$outstandingloans" },
    { $group: {
        _id: '$_id', 
        sum: { $sum: '$outstandingloans.balance' },
        count: { $sum: 1 }
    } },
    {$match: { sum : {$lt: -15000}, count: {$gte: 3}}},
    {$group: {_id: "$gender", Total: { $sum: 1 }}}
] );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM