【问题标题】:How to Count Instances in MongoDB如何计算 MongoDB 中的实例
【发布时间】:2018-10-06 11:02:32
【问题描述】:

如果我想总结 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 视图的聚合管道的步骤。

【问题讨论】:

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

标签: javascript mongodb aggregation


【解决方案1】:

以下任何一项都可以帮助您前进:

简单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
    }
})

【讨论】:

    【解决方案2】:

    您可以简单地使用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 的实例数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-04
      • 2021-12-27
      • 2022-11-26
      • 2010-12-24
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多