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

如何用MongoDB聚合函数按子数组元素值统计文档数量及分类?

Solution for MongoDB Aggregate Stats on Subarray valid Field

Got it! Here's a straightforward aggregate pipeline that will calculate the total document count, valid document count, and non-valid document count as you requested:

db.yourCollectionName.aggregate([
  // Add a flag indicating if the document has at least one valid item
  {
    $addFields: {
      isValid: {
        $anyElementTrue: {
          $map: {
            input: "$items",
            as: "item",
            in: "$$item.valid"
          }
        }
      }
    }
  },
  // Group all documents to compute the stats
  {
    $group: {
      _id: null,
      count: { $sum: 1 },
      valid: { $sum: { $cond: ["$isValid", 1, 0] } },
      nonValid: { $sum: { $cond: ["$isValid", 0, 1] } }
    }
  },
  // Remove the default _id field for cleaner output
  {
    $project: {
      _id: 0
    }
  }
])

Breakdown of Each Pipeline Stage:

  • $addFields: This stage creates a new field isValid for each document. We use $map to extract all valid values from the items array into a boolean array, then $anyElementTrue checks if any value in that array is true (meaning the document has at least one valid item).
  • $group: By grouping on _id: null, we aggregate all documents into a single group.
    • count uses $sum: 1 to tally the total number of documents.
    • valid uses $cond to add 1 for each document where isValid is true, otherwise 0.
    • nonValid does the opposite: adds 1 when isValid is false, otherwise 0.
  • $project: This stage removes the auto-generated _id field from the final result to match your desired output format.

Expected Output:

When running this pipeline against your sample data, you'll get exactly what you need:

{ "count" : 3, "valid" : 2, "nonValid" : 1 }

内容的提问来源于stack exchange,提问作者Shamnad P S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:14:13