Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query For Total User Count Day By Day In MongoDB

I have "users" collection and i want day by day total user count eg:

01.01.2012 -> 5
02.01.2012 -> 9
03.01.2012 -> 18
04.01.2012 -> 24
05.01.2012 -> 38
06.01.2012 -> 48

I have createdAt attritube for each user. Can you help me about the query ?

{ 
  "_id" : ObjectId( "5076d3e70546c971539d9f8a" ),
  "createdAt" : Date( 1339964775466 ),
  "points" : 200,
  "profile" : null,
  "userId" : "10002"
}
like image 265
mTuran Avatar asked Dec 19 '25 00:12

mTuran


2 Answers

here this is works for, day by day count data

output i got:

30/3/2016   4
26/3/2016   4
21/3/2016   4
12/3/2016   12
14/3/2016   18
10/3/2016   10
9/3/2016    11
8/3/2016    19
7/3/2016    21

script:

model.aggregate({
  $match: {
    createdAt: {
      $gte: new Date("2016-01-01")
    } 
  } 
}, { 
  $group: {
    _id: { 
      "year":  { "$year": "$createdAt" },
      "month": { "$month": "$createdAt" },
      "day":   { "$dayOfMonth": "$createdAt" }
    },
    count:{$sum: 1}
  }
}).exec(function(err,data){
  if (err) {
    console.log('Error Fetching model');
    console.log(err);
  } else {
    console.log(data);
  }
});
like image 50
Vinay Pandya Avatar answered Dec 20 '25 16:12

Vinay Pandya


You have a couple of options, in order of performance :

  1. Maintain the count in seperate aggregation documents. Every time you add a user you update the counter for that day (so, each day has its unique counter document in a, say, a users.daycounters collection). This is easily the fastest approach and scales best.
  2. In 2.2 or higher you can use the aggregation framework. Examples close to your use case are documented here. Look for the $group operator : http://docs.mongodb.org/manual/applications/aggregation/
  3. You can use the map/reduce framework : http://www.mongodb.org/display/DOCS/MapReduce. This is sharding compatible but relatively slow due to the JavaScript context use. Also it's not very straightforward for something as simple as this.
  4. You can use the group() operator documented here : http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Group. Since this does not work in a sharded environment and is generally slow due to the use of the single-threaded JavaScript context this is not recommended.
like image 41
Remon van Vliet Avatar answered Dec 20 '25 16:12

Remon van Vliet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!