【问题标题】:Grab count of a specific field in database抓取数据库中特定字段的计数
【发布时间】:2021-06-22 21:08:52
【问题描述】:

所以我有一个架构,并且在该架构中有一个名为“caseCount”的对象,带有一个数字值。我只是想获取“caseCount”的每个对象的每个值并将其相加。有人能指出我正确的方向吗?如果我需要解释更多,我很乐意这样做。谢谢!

架构:

const Profile = Schema({
    userID: String,
    messageCount: Number,
    caseCount: Number,
    Skins: Array,
});

代码:

const data = Profiles.collection.aggregate([{
      $group: {
        _id: '$id',
        totalCaseCount: { $sum: '$caseCount' }
      }
    }]);

【问题讨论】:

  • 请分享您的示例架构。
  • 刚刚更新了。

标签: node.js mongodb mongodb-query aggregation-framework mongoose-schema


【解决方案1】:

演示 - https://mongoplayground.net/p/7TnpQl3tJHt

在聚合查询中使用$sum

$group

db.collection.aggregate({
  $group: {
    _id: null,
    toatalCaseCount: {  $sum: "$caseCount" }
  }
})

Profiles.collection.aggregate([{
  $group: {
    _id: null,
    totalCaseCount: { $sum: '$caseCount' }
  }
  }], function(err, data) {
   console.log(data); // here you'll get your data from the query
});

【讨论】:

  • 所以我这样做了,当我 console.logged 时,它给了我这个 Aggregate { _pipeline: [ { '$group': [Object] } ], _model: Model { Profiles }, options : {} }
  • @chai_turtlep 将您的 nodejs 代码添加到问题中。
  • 我怎样才能让它只记录“totalCaseCount”的值?
  • @chai_turtlep 你现在在日志上得到了什么? data[0].totalCaseCount
  • 嗨@TusharGupta-curioustushar 您在猫鼬代码中按$id 而不是null 对记录进行分组。
猜你喜欢
  • 1970-01-01
  • 2017-12-08
  • 1970-01-01
  • 2020-12-04
  • 2019-05-11
  • 1970-01-01
  • 2020-03-29
  • 2020-04-25
  • 1970-01-01
相关资源
最近更新 更多