【问题标题】:sql conversion to mongodb aggregatesql转换为mongodb聚合
【发布时间】:2021-11-25 22:53:17
【问题描述】:

我是 SQL 和 MongoDB 的新手。我正在尝试转换:

SELECT accountType, ROUND(AVG(balance), 2) avgBalance
FROM customers
WHERE gender="female"
GROUP BY accountType
HAVING COUNT(*) < 140
ORDER BY avgBalance
LIMIT 1 

MongoDB 但我无法让它工作。我不太明白顺序($group、$match、$project、$round、$avg 等)应该如何以及“ROUND 和 AVG”如何一起使用。答案应该是这样的: { "accountType" : "account-type", "avgBalance" : NumberDecimal("9999.99") }

这是我目前所拥有的:

db.customers.aggregate( [ { $group: { _id: { accountType: "accountType", avgBalance: { $avg: { "balance" } } }, { $match: { count: { $lt: 140 } } }, { gender: "female" }, { $project: { "accountType": { $round: [ $agv: "balance", 2 ] } } }, { $limit: 1 } ] )

【问题讨论】:

    标签: sql mongodb


    【解决方案1】:

    方向还不错,会是这个:

    db.customers.aggregate([
       //  WHERE gender="female"
       { $match: { gender: "female" } },
       // GROUP BY accountType, SELECT AVG(balance)
       {
          $group: {
             _id: "$accountType",
             avgBalance: { $avg: "$balance" },
             count: {$sum: 1}
          }
       },
       // HAVING COUNT(*) < 140
       { $match: { count: { $lt: 140 } } },
       // SELECT ... AS ...
       {
          $project: {
             accountType: "$_id",
             avgBalance: { $round: ["$avgBalance", 2] }
          }
       },
       // ORDER BY avgBalance
       { $sort: { avgBalance: 1 } },
       // LIMIT 1
       { $limit: 1 }
    ])
    

    【讨论】:

    • 谢谢! :-) 我对其进行了一些修改以使其具有正确的形式,但 avgBalance 给了我“null”,我不知道为什么。这是修改后的mongo: db.customers.aggregate([ { $match: { gender: "female" } }, { $group: { _id: "$accountType", avgBalance: { $avg: "$balance" }, count: {$sum: 1} } }, { $match: { count: { $lt: 140 } } }, { $project: { _id: 0, accountType: "$_id", avgBalance: { $round: [ "$balance", 2] }}}, { $sort: { avgBalance: 1 } }, { $limit: 1 }])
    • 可能是因为这个:"balance" : NumberDecimal("3485.90")?
    • 请编辑您的问题并添加附加代码。还请提供一些示例输入数据。查看我的更新 -> avgBalance: { $round: ["$avgBalance", 2] }.
    • 感谢您的建议。我没有注意到可以编辑原始问题。对于那个很抱歉。感谢您的更新,我已经尝试了几乎所有我能想到的东西,但不是那样。
    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 2017-01-25
    • 2015-10-09
    • 1970-01-01
    • 2019-08-09
    • 2019-03-15
    • 2014-07-31
    • 2021-09-03
    相关资源
    最近更新 更多