如何计算 MongoDB 中的实例

How to Count Instances in MongoDB

如果我想对 MongoDB 中的数值求和,我会这样做:

totalOpenBalance: {
  $sum: "$openBalance"
} // sum up all "openBalance" values

但我想知道的是,当我想对某事的实例求和时,我使用什么运算符?假设我有一个 属性,例如 customer_id,并且数据如下所示:

{
   "customer_id" : 445,
   "other_prop" : value
},
{
   "customer_id" : 446,
   "other_prop" : value
},

请注意,我不想汇总分配给 "customer_id" 的值,而是统计数据集合中有多少 "customer_id" 实例。换句话说,根据上面的数据,我应该得到“2”作为我的输出。我使用什么运算符来做到这一点?

澄清一下,这是我需要添加到用于生成 mongo 视图的聚合管道的步骤。

以下任何一项都可以让您继续:

简单find:

db.collection.find({
    "customer_id": { $exists: true }
}).count()

$count 合计:

db.collection.aggregate({
    $match: {
        "customer_id": { $exists: true }
    }
}, {
    $count: "numberOfInstances"
})

$group 合计:

db.collection.aggregate({
    $match: {
        "customer_id": { $exists: true }
    }
}, {
    $group: {
        _id: null,
        "numberOfInstances": { $sum: 1 } // count instances
    }
})

您可以简单地使用 find$exists 然后计算返回的行数

db.collection.find( { customer_id: { $exists: true } } ).count()

或者如果你想使用聚合(我认为你不应该为这样简单的任务做)这就是你可以做的。

db.collection.aggregate({
    $match: {
        "customer_id": {
            $exists: true
        }
    }
}, {
    $group: {
        _id: null,
        "total": {
            $sum: 1
        } 
    }
})

这里total属性会给你包含customer_id的实例数量