Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb aggregation $unwind then count

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,

like image 488
Owumaro Avatar asked Dec 05 '14 10:12

Owumaro


People also ask

Can we use count with aggregate function in MongoDB?

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.

How do I count documents in MongoDB aggregation?

The $count stage returns a count of the remaining documents in the aggregation pipeline and assigns the value to a field called passing_scores .

Is aggregation slow in MongoDB?

Aggregation is slow - Working with Data - MongoDB Developer Community Forums.

What does $unwind do in MongoDB?

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.


1 Answers

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 } } }])
like image 60
Jehof Avatar answered Oct 11 '22 00:10

Jehof