Mongodb how to find how much days ago from a timestamp field -


i trying find number of days ago using timestamp dont know how ?

{     "_id" : objectid("5504cc9ddd5af617caae30b3"),     "session_id" : 1,     "timestamp" : "2014-04-07t10:51:09.277z",     "item_id" : 214536502,     "category" : 0 } 

how can calculate number of days ago using field "timestamp" ?

you may use aggregate, $project new date() on timestamp field, calculation, this:

pipe = {     "$project" : {         "_id" : 1,         "daysince" : {             "$divide" : [                 {                     "$subtract" : [                         new date(),                         new date("$timestamp")                     ]                 },                 86400000             ]         }     } } 

to calculate:

db.collection.aggregate(pipeline=pipe) 

since timestamp isn't isodate object, need convert one, subtract current date, , divide result 60*60*24*1000, number of days since today.

you can change new date() need compared.

updated:

since believe timestamp format might malformed, alternatively may use mapreduce functions calculate this:

// in mongo shell using db  var maptimestamp = function() {      daysince = parseint(new date() - new date(this.timestamp) / 86400000);     emit(this._id, daysince);  } // since map reduce on 1 field, there's no need var reducetimestamp = function (key, value) { return value; }  db.collection.mapreduce(maptimestamp, reducetimestamp, {out: "sample"}) 

to show results:

db.sample.find() 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -