如何用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
isValidfor each document. We use$mapto extract allvalidvalues from theitemsarray into a boolean array, then$anyElementTruechecks if any value in that array istrue(meaning the document has at least one valid item). - $group: By grouping on
_id: null, we aggregate all documents into a single group.countuses$sum: 1to tally the total number of documents.validuses$condto add 1 for each document whereisValidistrue, otherwise 0.nonValiddoes the opposite: adds 1 whenisValidisfalse, otherwise 0.
- $project: This stage removes the auto-generated
_idfield 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
相关产品推荐
相关产品推荐

