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

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 $exists to check if each target object is present. If it is, we add 1 to the documentCount; 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 the documentCount values together to get the grand total of occurrences.
  • Final $project Stage: This just removes the auto-generated _id field 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 yourCollectionName with the actual name of your MongoDB collection.
  • This method works even if the objects have nested fields — $exists checks for the presence of the field itself, regardless of what's inside it.

内容的提问来源于stack exchange,提问作者Siraj ul Haq

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:11:30