【问题标题】:How to count the number of documents with the specified field in MongoDB?如何统计MongoDB中具有指定字段的文档数?
【发布时间】:2020-10-06 18:57:23
【问题描述】:

考虑集合“项目”中的以下文档

{
  _id:"1",
  "project_id":"1",
  "Name":"A",
  "type":"Description"
}

{
  _id:"2",
  "Name":"A",
  "project_id":"2",
  "type":"Paragraph"
}

{
  _id:"3",
  "Name":"A",
  "project_id":"1",
  "type":"Description"
}

{
  _id:"4",
  "Name":"A",
  "project_id":"3",
  "type":"Description"
}

我想编写一个 mongodb 查询,它必须计算 "project_id":"1" 的 "type":"Description" 的文档数。

【问题讨论】:

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

您可以使用以下任何一种方法来查找计数:

  1. 使用db.collection.countDocuments(query, options)
db.collection.countDocuments({ "project_id": "1","type":"Description"})

它执行文档的聚合以返回准确的计数

  1. 使用db.collection.count(query, options)
db.collection.count({ "project_id": "1","type": "Description" })

避免在没有查询谓词的情况下使用 db.collection.count() 方法,因为没有查询谓词,该方法会根据集合的元数据返回结果,这可能会导致近似计数。

  1. 使用aggregation pipeline stage $count
db.collection.aggregate([
  {
    $match: {
      "project_id": "1",
      "type": "Description"
    }
  },
  {
    $count: "count"
  }
])

MongoDB Query

PS:将“收藏”替换为您的收藏名称。

【讨论】:

  • 只有countDocuments 保证准确,并且实际上在幕后使用了聚合管道之类的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-14
  • 1970-01-01
  • 1970-01-01
  • 2016-06-18
相关资源
最近更新 更多