Question

I need to unwind an array in order to do a group by in some existing code using the mongo Collection.Group() method.

I have a document like:

{
    "_id" : "5373c4fdcb080a06d471c07b",
    "Form" : "Form 1",
    "Values" : {
        "Name" : "Bob Smith",
        "FavColors" : [ 
            "green",
            "blue"
        ]
    }
}

I need to unwind the FavColors array and group by FavColors in order to get a count like this:

green 1
blue 1

I understand this can easily be completed using the aggregation framework, but is there anyway to unwind an array using Collection.Group() in the C# driver or db.Collection.Group() in you are in the mongo shell? i.e. Is there anything analogous to $unwind from the aggregation framework in the .group operator?

Was it helpful?

Solution

This is how you do it:

function groupByFavColors(host){
 var conn = new Mongo(host);
 var db = conn.getDatabase("DB-NAME");

 var res = db.product.aggregate([
     {
         // unwind the array
         $unwind: '$Values.FavColors',
     },
     {
         // group by..
         $group: {
             _id: '$Values.FavColors',

             num_sold: {
                 $sum: 1
             }
         }
     }
 ]);

 printjson(res);

}

print("usage: groupbyFavColors(string host);")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top