4.3. Using an ISO Formatted Date for Document IDs

The ISO 8601 date standard describes a useful scheme for representing a date string in a Year-Month-DayTHour:Minute:Second.microsecond format. For time-bound documents in a CouchDB database this can be a very handy way to create a unique identifier, since JavaScript can directly use it to create a Date object. Using this sample map function:

  1. function(doc) {
  2. var dt = new Date(doc._id);
  3. emit([dt.getDate(), doc.widget], 1);
  4. }

simply use group_level to zoom in on whatever time you wish to use.

  1. curl -X GET "http://localhost:5984/transactions/_design/widget_count/_view/toss?group_level=1"
  2. {"rows":[
  3. {"key":[20],"value":10},
  4. {"key":[21],"value":20}
  5. ]}
  6. curl -X GET "http://localhost:5984/transactions/_design/widget_count/_view/toss?group_level=2"
  7. {"rows":[
  8. {"key":[20,widget],"value":10},
  9. {"key":[21,widget],"value":10},
  10. {"key":[21,thing],"value":10}
  11. ]}

Another method is using parseint() and datetime.substr() to cut out useful values for a return key:

  1. function (doc) {
  2. var datetime = doc._id;
  3. var year = parseInt(datetime.substr(0, 4));
  4. var month = parseInt(datetime.substr(5, 2), 10);
  5. var day = parseInt(datetime.substr(8, 2), 10);
  6. var hour = parseInt(datetime.substr(11, 2), 10);
  7. var minute = parseInt(datetime.substr(14, 2), 10);
  8. emit([doc.widget, year, month, day, hour, minute], 1);
  9. }