Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mongodb - "group by" queries on meteor collection

My data mongoDB:

>db.CUSTOMER.find()

{"Name": "A", "CreatedDate": "Wed Jan 29 2014"}

{"Name": "B", "CreatedDate": "Fri Jan 31 2014"}

{"Name": "C", "CreatedDate": "Sat Feb 01 2014"}

{"Name": "D", "CreatedDate": "Sat Feb 01 2014"}

In meteor:

Customer = new Meteor.Collection("CUSTOMER");

I'm trying to group them by date (Mon, Tues, Wed, ...) in meteor collection along with the total of the data. It should be something like this:

{"Date": "Wed Jan 29 2014", "Total" 1}

{"Date": "Fri Jan 31 2014", "Total" 1}

{"Date": "Sat Feb 01 2014", "Total" 2}

In mongoDB, I'd just go with http://docs.mongodb.org/manual/reference/method/db.collection.group/, but apparently, it is impossible in meteor, for it doesn't support findAndModify, upsert, aggregate functions, and map/reduce.

Is there any examples of workaround that I can do to make it works?

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll need to group them manually. There are a number of ways to do that, but here's an (admittedly difficult to read) example:

var customers = Customer.find().fetch();

var groupedDates = _.groupBy(_.pluck(customers, 'CreatedDate'));

_.each(_.values(groupedDates), function(dates) {
  console.log({Date: dates[0], Total: dates.length});
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...