taktouk
taktouk

Reputation: 21

how to use the aggregation of mongodb with meteor

i'm using Meteorjs and mongo I have a collection structure like this:

{
    "_id" : "LxMaZhRX7ZbAkiFqF",
    "categorie" : "International matches",
    "division" : [
            {
                    "nameDivision" : "div 1",
                    "type" : "Championat"
            },
            {
                    "nameDivision" : "div 2",
                    "type" : "Coupe"
            },
            {
                    "nameDivision" : "div 3",
                    "type" : "Championat"
            },
            {
                    "nameDivision" : "div 4",
                    "type" : "Championat"
            }
    ]
   }

I want to have this result in my subscription:

{
    "_id" : "LxMaZhRX7ZbAkiFqF",
    "categorie" : "International matches",
    "division" : [
            {
                    "type" : "Championat",
                    division:[{
                        "nameDivision" : "div 1",
                        "nameDivision" : "div 3",
                        "nameDivision" : "div 4",
                    }]

            },
            {
                 "type" : "Coupe",
                  "division":[{
                     "nameDivision" : "div 2",
                    }]  


            },
            {
    ]
   }

I need your help on how to use the function with mongodb aggegate to group the Elements thank you

Upvotes: 1

Views: 50

Answers (1)

chridam
chridam

Reputation: 103305

In Meteor, you can use the meteorhacks:aggregate package to implement the aggregation:

Add to your app with

meteor add meteorhacks:aggregate

Then simply use .aggregate function like below.

var coll = new Mongo.Collection('collectionName');
var pipeline = [
    { "$unwind": "$division" },
    {
        "$group": {
            "_id": "$division.type",
            "id": { "$first": "$_id" },
            "categorie": { "$first": "$categorie" },
            "division": { 
                "$push": { "nameDivision": "$division.nameDivision" }
            }
        }
    },
    {
        "$group": {
            "_id": "$id",               
            "categorie": { "$first": "$categorie" },
            "division": { 
                "$push": { 
                    "type": "$_id",
                    "division": "$division"
                }
            }
        }
    }
];
var result = coll.aggregate(pipeline);

Upvotes: 2

Related Questions