1

I have several records on the mongoDB. I need to know the no of records present on each date.I know that we can get the date from _id field.Please help me how to do this ?

1
  • 1
    What is your document scructure? Commented Aug 20, 2014 at 15:35

1 Answer 1

1

You can do it with MongoDB Map-Reduce feature, using ObjectID::getTimestamp() method to determine insertion time.

Here is an example of doing so:

db.runCommand({
  mapreduce: 'collection',
  map: function() {
    var created = this._id.getTimestamp();
    var date = created.toISOString().slice(0, 10);
    return emit(date, 1);
  },
  reduce: function(key, vals) {
    return Array.sum(vals);
  },
  out: {
    inline: 1
  }
})

I'm using Date::toISOString() method to convert insertion date into ISO date string

2014-07-21T12:39:21.000Z

and String::slice() method to take first 10 characters of it

2014-07-21

The resulting output of this Map-Reduce task should look like this:

[
  {
    "_id" : "2014-07-21", // date
    "value" : 100011 // number of documents
  },
  ...
]
Sign up to request clarification or add additional context in comments.

3 Comments

It seems fine. I want to achieve the same in a .js file.The output should be of the format date1, count date2,count date3,count etc.
@prashantas What do you mean by .js file? Do you mean node.js script, or just a .js file executed in mongo shell?
It is just a .js file. Anyway I found the solution with your help.Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.