Use mongodb aggregation structure to group by array length

I have a collection that looks something like this:

{ "_id": "id0", "name": "...", "saved_things": [ { ... }, { ... }, { ... }, ] } { "_id": "id1", "name": "...", "saved_things": [ { ... }, ] } { "_id": "id2", "name": "...", "saved_things": [ { ... }, ] } 

etc...

I want to use the mongodb aggregation structure to get a histogram result that tells how many users have a certain number of saved_things . For example, for the dataset above, it might return something like:

 { "_id": 1, "count": 2 }, { "_id": 3, "count": 1 } 

I tried various combinations of aggregate functions like the ones below, but none of them worked out correctly. (I have the feeling that I'm terribly wrong about that.)

 collection.aggregate([ { $unwind: "$saved_things" }, { $group: "$_id", count: { $sum: 1 } } }, { $group: "$count", number: { $sum: 1 } } }, { $sort: { number: -1 } } ], function(err, result) { console.log(result); }); 

Is this possible with the Mongo aggregate structure, or will I be better off with the map reduction feature?

+6
source share
1 answer

Ok, got it! Like this. The aggregation conveyor is basically as follows:

 { $unwind: "$saved_things" }, { $group: { _id: "$_id", size: { $sum: 1 } } }, { $group: { _id: "$size", frequency: { $sum: 1 } } }, { $project: { size: "$_id", frequency: 1, _id: 0 } } 

Unwind the saved_things array, then group by the _id document and count it, so we can achieve the size of the array. Now easy, group size and count the frequency. Use the project to rename the _id field to size .

+5
source

Source: https://habr.com/ru/post/950654/


All Articles