You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB集合中统计医生姓名总数的查询方法求助

正确统计MongoDB中所有医生姓名的总数

Got it, let's fix this for you! Your original query only counts how many companies have a doctors field, but we need to tally up every individual doctor across all those companies. Here are two solid methods using MongoDB's aggregation framework to get the total number of doctors:

Method 1: Unwind the Array & Count Individual Entries

This approach expands the doctors array into separate documents (one per doctor), then counts all those expanded entries. It’s great if you might later want to add filters for specific doctor attributes (like salutation or name):

db.your_collection_name.aggregate([
  // Optional but recommended: Only include docs where doctors is a valid array
  { $match: { doctors: { $exists: true, $type: "array" } } },
  // Unwind the doctors array—each doctor becomes its own document
  { $unwind: "$doctors" },
  // Count all the unwound doctor records
  { $count: "total_doctors" }
])

Method 2: Calculate Array Sizes & Sum Them Up

If you don’t need to process individual doctor data, this method is more efficient. It first calculates how many doctors are in each company’s array, then sums those numbers across all documents:

db.your_collection_name.aggregate([
  { $match: { doctors: { $exists: true, $type: "array" } } },
  // Add a field that tracks the number of doctors per company
  { $project: { num_doctors: { $size: "$doctors" } } },
  // Sum all the per-company doctor counts to get the total
  { $group: { _id: null, total_doctors: { $sum: "$num_doctors" } } },
  // Optional: Clean up output by hiding the _id field
  { $project: { _id: 0, total_doctors: 1 } }
])

Quick Tips:

  • Adding $type: "array" to the $match stage prevents errors from documents where doctors exists but isn’t an array (like a string or null).
  • Don’t forget to replace your_collection_name with the actual name of your MongoDB collection.

内容的提问来源于stack exchange,提问作者Chris_Du

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:26:12