Publish with aggregate, project and groupby

Dear All,

I am having problems when I try to create a publish function with groupby and project on aggregate.

For Example, if I execute the following mongo aggregate it works as expected:

> db.Tickets.aggregate(
>    [
>      {
>        $project: {
>           time: { 
>               $concat: [ 
>               { "$substr": [ { "$year": "$createdAt" }, 0, 4 ] },
>                  '-',
>               { "$substr": [ { "$month": "$createdAt" }, 0, 2 ]}
>                ]}
>            }
>       },
>       {
>        $group: {
>           _id: "$time",
>           count: {$sum:1}
>            }
>       }
>    ]
> )

However when I try to pass that mongo code to meteor as a Publish function, I am not getting results, here is my puslish function:

> Meteor.publish("Chart2", function () {
>     var sub = this;
>     var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;


>     var pipeline = [
>         {"$project":{"time":{"$concat":[{ "$substr": [ { "$year": "$createdAt" }, 0, 4 ] },' - ',{ "$substr": [ { "$month": "$createdAt" }, 0, 2 ]}]}}},
>         {"$group": {"_id": "$time","count":{"$sum": 1}}}
>         ];

>     db.collection("Tickets").aggregate(
>         pipeline,
>         // Need to wrap the callback so it gets called in a Fiber.
>         
>         Meteor.bindEnvironment(
>             function (err, result) {
>                 // Add each of the results to the subscription.
>                 _.each(result, function (e) {
>                     // Generate a random disposable id for aggregated documents
>                     sub.added("Chart2", Random.id(), {
>                         "time": e.time,
>                         "value": e.count
>                     });
>                 });
>                 sub.ready();
>             },
>             function (error) {
>                 console.log("Error doing aggregation: " + error);
>             }
>         )
>     );
>     
> });

Could someone help me? I really appreciate all your help and time on this matter.

If you have any question just let me know,

have a great day.

Issue resolved. Thank you :slight_smile:

could you show how it was resolved?

Hi Kamil123,

 Sure, I have performed the action just creating the variable on this way:
 var pipeline = [
             {"$match":{"area": "Car"}},
         {"$project":{"time":{"$concat":[{ "$substr": [ { "$year": "$createdAt" }, 0, 4 ] },' - ',{ "$substr": [ { "$month": "$createdAt" }, 0, 2 ]}]}}},
         {
             "$group": {
                 "_id": "$time",
                 "count": {
                     "$sum": 1
                 }
             }
         },
        {"$sort":{"_id":1}}
         ];

Hope it helps you :slight_smile:. Have a great day.