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$matchstage prevents errors from documents wheredoctorsexists but isn’t an array (like a string or null). - Don’t forget to replace
your_collection_namewith the actual name of your MongoDB collection.
内容的提问来源于stack exchange,提问作者Chris_Du

