【问题标题】:MongoDb count percent of document with a certain field present存在特定字段的文档的 MongoDb 计数百分比
【发布时间】:2020-06-29 08:46:34
【问题描述】:

我有一些 MongoDb 文档(代表订单),它们的架构大致如下:

{
   id: ObjectID
   exchange_order_products: Array
}

如果客户没有交换他订购的任何商品,则 exchange_order_products 数组为空,或者如果他们交换了,则该数组将包含每个交换商品的 Object。

我想获取客户没有交换任何东西的订单百分比,例如exchange_order_products 数组为空。

所以基本上公式如下:(Number Of Orders With At Least One Exchange * 100) / Number of Orders With No Exchanges

我知道我可以像这样计算 exchange_order_products 数组为空的订单数量:

[{$match: {
   exchange_order_products: {$exists: true, $size: 0}
}}, {$count: 'count'}]

但是如何同时获取我的集合中所有文档的数量?

【问题讨论】:

  • 我猜正确的公式是:Nº empty array * 100 / total

标签: database mongodb mongodb-query aggregation-framework


【解决方案1】:

您可以使用$group$sum 以及$cond 分别计算空的和非空的。那么你需要$multiply$divide来计算百分比:

db.collection.aggregate([
    {
        $group: {
            _id: null,
            empty: { $sum: { $cond: [ { $eq: [ { $size: "$exchange_order_products" }, 0 ] }, 1, 0 ] } },
            nonEmpty: { $sum: { $cond: [ { $eq: [ { $size: "$exchange_order_products" }, 0 ] }, 0, 1 ] } },
        }
    },
    {
        $project: {
            percent: {
                $multiply: [
                    100, { $divide: [ "$nonEmpty", "$empty" ] }
                ]
            }
        }
    }
])

Mongo Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    相关资源
    最近更新 更多