MongoDB:统计集合中指定对象的总数量
Solution to Count Total Occurrences of obj1, obj2, obj3 in MongoDB
Got it, let's break down how to calculate the total number of times obj1, obj2, and obj3 appear across your collection. Since a single document can have multiple of these objects (like your first document with both obj1 and obj2), we'll use MongoDB's aggregation framework to tally them up accurately.
Aggregation Query
db.yourCollectionName.aggregate([ // Step 1: Count how many target objects exist in each document { $project: { documentCount: { $sum: [ { $cond: [{ $exists: ["$obj1", true] }, 1, 0] }, { $cond: [{ $exists: ["$obj2", true] }, 1, 0] }, { $cond: [{ $exists: ["$obj3", true] }, 1, 0] } ] } } }, // Step 2: Sum all document-level counts to get the total { $group: { _id: null, totalOccurrences: { $sum: "$documentCount" } } }, // Optional: Clean up the output to hide the default _id field { $project: { _id: 0 } } ])
How This Works
- $project Stage: For every document, we use
$existsto check if each target object is present. If it is, we add 1 to thedocumentCount; if not, we add 0. We then sum those values to get how many of the target objects are in that single document. - $group Stage: We group all documents into one single group (using
_id: null) and sum all thedocumentCountvalues together to get the grand total of occurrences. - Final $project Stage: This just removes the auto-generated
_idfield from the output to make it cleaner.
Example Output
For your sample documents, this query will return exactly what you're expecting:
{ "totalOccurrences" : 5 }
Quick Notes
- Don't forget to replace
yourCollectionNamewith the actual name of your MongoDB collection. - This method works even if the objects have nested fields —
$existschecks for the presence of the field itself, regardless of what's inside it.
内容的提问来源于stack exchange,提问作者Siraj ul Haq
相关产品推荐
相关产品推荐

