Organizational Research By

Surprising Reserch Topic

inserting and querying date with mongodb and nodejs

inserting and querying date with mongodb and nodejs  using -'javascript,node.js,mongodb,date'

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){
   } 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){
  } else  {
    console.log('not found');

Nothing comes back either. What am I doing wrong please?


asked Sep 18, 2015 by mca.agarwal
0 votes

Related Hot Questions

2 Answers

0 votes

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:

answered Sep 18, 2015 by nikhilapatil
0 votes

To clarify. What is important to know is that:

  • Yes, you have to pass a Javascript Date object.
  • Yes, it has to be ISODate friendly
  • Yes, from my experience getting this to work, you need to manipulate the date to ISO
  • Yes, working with dates is generally always a tedious process, and mongo is no exception

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());
    'date': { $lte: inputDate }
answered Sep 18, 2015 by sujata naik