I need some help finding a record by date in mongodb and nodejs.
I add the date to the json object in a scraping script as follows:
jsonObj.last_updated = new Date();
This object is inserted into mongodb. I can see it as follows:
"last_updated" : "2014-01-22T14:56:59.301Z"
Then in my nodejs script I do a findOne():
var jObj = JSON.parse(line.toString()); collection.findOne(jObj,function(err, doc) { if (doc){ console.log(doc._id); } else { console.log('not found'); } });
The object is not found. If I remove the last_updated field from the object it is found so it is definitely where the problem is.
If I isolate the field as follows:
collection.findOne({last_updated: '2014-01-22T14:56:59.301Z'},function(err, doc) { if (doc){ console.log(doc._id); } else { console.log('not found'); } });
Nothing comes back either. What am I doing wrong please?
The best format to store date and time in MongoDB is native javascript Date() or ISO date format as it internally converts it into BSON native Date object.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
You need to pass a date object and not a date string.
collection.findOne({last_updated: new Date('2014-01-22T14:56:59.301Z')},function(err, doc) {
The MongoDB driver will transform it into ISODate
:
{ "_id" : ObjectId("52dfe0c469631792dba51770"), "last_updated" : ISODate('2014-01-22T14:56:59.301Z') }
Check these questions:
To clarify. What is important to know is that:
Here is a working snippet of code, where we do a little bit of date manipulation to ensure Mongo can handle it correctly. In this example, I am using mongoose module and want results for rows whose date attribute is less than (ie. before) the date given as myDate param.
var inputDate = new Date(myDate.toISOString()); MyModel.find({ 'date': { $lte: inputDate } })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With