Here is my problem : in my Mongo database, I have a collection with items like :
{
'id': 1,
'steps': [
{
action: 'start',
info: 'foo'
},
{
action: 'stop',
info: 'bar'
}
]
}
I would like to get the total number of steps 'start'.
I tryed to use the MongoDB aggregation framework : I use $unwind
on steps.action
and $match
on steps.action
to match 'start'.
However, I get too much data and reach the aggregation's limit :
exception: aggregation result exceeds maximum document size (16MB)
. I don't need the data, I just want the count, but I couldn't find how to do it (tryed with $group without success).
Thanks in advance,
MongoDB $count AggregationThe MongoDB $count operator allows us to pass a document to the next phase of the aggregation pipeline that contains a count of the documents. There a couple of important things to note about this syntax: First, we invoke the $count operator and then specify the string.
The $count stage returns a count of the remaining documents in the aggregation pipeline and assigns the value to a field called passing_scores .
Aggregation is slow - Working with Data - MongoDB Developer Community Forums.
The MongoDB $unwind operator is used to deconstruct an array field in a document and create separate output documents for each item in the array.
If you want the count you can use this
db.test.count({"steps.action":"start"})
but this will not take into account if steps contain multiple steps with action start
.
When you also need to count all steps with start
then you need to unwind the array, make a match on steps.action and then group the results to count.
db.test.aggregate([{$unwind:"$steps"}, {$match:{"steps.action":"start"}},{ $group: { _id: null, count: { $sum: 1 } } }])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With