How to use rawCollection properly?


#1

I want to use Mongo’s db.collection.group. As far as I understand from 1.0.4 Meteor allow to direct access to the collection and database objects from the npm Mongo driver via new rawCollection.

On `meteor mongo’ shell I can use:

db.orders.group({
  keyf: function(doc) {return {year:doc.createdAt.toISOString().substring(0, 4)}},
  initial: {months:{}},
  reduce: function(order, result) {
    var month = order.createdAt.getMonth()+1,
        date = order.createdAt.getDate();

    month = result.months[month] || (result.months[month] = {});
    date = month[date] || (month[date] = []);
    date.push(order);
  },
  cond: {$and: [{createdAt: {$gt: new Date("2015-02-01")}, createdAt: {$lt: new Date("2015-02-25")}}]}
})

How could I get same effect from my code (server) or meteor shell?

Is this util proper way to get group on collection?

Mongo.Collection.prototype.group = (grouping) ->
  collection = @rawCollection()
  Meteor.wrapAsync(collection.group.bind(collection))(grouping)

#2

You might just be losing the context by trying to bind inside of Meteor.wrapAsync(). You can pass a second argument to set the context.

If that is not the issue you can look at my implementation or look at code from any other aggregation package to see how it is being done.


#3

Thanks for StackOverflow I found the problem.
The group method in the node driver is different from in the shell for some reason. More complete answer here: http://stackoverflow.com/questions/29295143/how-to-do-mongo-group-on-meteor-server-side/29295707