Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group count with MongoDB using aggregation framework

Let's say my MongoDB schema looks like this:

{car_id: "...", owner_id: "..."} 

This is a many-to-many relationship. For example, the data might look like this:

+-----+----------+--------+ | _id | owner_id | car_id | +-----+----------+--------+ |   1 |        1 |      1 | |   2 |        1 |      2 | |   3 |        1 |      3 | |   4 |        2 |      1 | |   5 |        2 |      2 | |   6 |        3 |      4 | |   7 |        3 |      5 | |   8 |        3 |      6 | |   9 |        3 |      7 | |  10 |        1 |      1 | <-- not unique +-----+----------+--------+ 

I want to get the number of cars owned by each owner. In SQL, this might look like:

SELECT owner_id, COUNT(*) AS cars_owned FROM (SELECT owner_id FROM car_owners GROUP BY owner_id, car_id) AS t GROUP BY owner_id; 

In this case, the result would look like this:

+----------+------------+ | owner_id | cars_owned | +----------+------------+ |        1 |          3 | |        2 |          2 | |        3 |          4 | +----------+------------+ 

How can I accomplish this same thing using MongoDB using the aggregation framework?

like image 484
Matthew Ratzloff Avatar asked Nov 05 '12 20:11

Matthew Ratzloff


People also ask

Can we use count with aggregate function in MongoDB?

MongoDB aggregate $count element in array For this, MongoDB provides the $size aggregation to count and returns the total number of items in an array. Let's get understand this with the help of an example. Example: The subsequent documents were inserted into the Test collection.

How do I get group count in MongoDB?

MongoDB group by count multiple fields In MongoDB for counting the multiple fields, we use the aggregation() function. Here, $count is used to count the fields. Example: In this example, we stored some documents in the student collection and use the find() method to check how many documents are in our collection.

How do I group values in MongoDB?

Use the _id field in the $group pipeline stage to set the group key. See below for usage examples. In the $group stage output, the _id field is set to the group key for that document. The output documents can also contain additional fields that are set using accumulator expressions.


1 Answers

To accommodate the potential duplicates, you need to use two $group operations:

db.test.aggregate([     { $group: {         _id: { owner_id: '$owner_id', car_id: '$car_id' }     }},     { $group: {         _id: '$_id.owner_id',         cars_owned: { $sum: 1 }     }},     { $project: {         _id: 0,         owner_id: '$_id',         cars_owned: 1     }}]     , function(err, result){         console.log(result);     } ); 

Gives a result with a format of:

[ { cars_owned: 2, owner_id: 10 },   { cars_owned: 1, owner_id: 11 } ] 
like image 99
JohnnyHK Avatar answered Sep 28 '22 05:09

JohnnyHK