1

I want to find document in a mongodb table using node js. I'm currently working with mongojs plugin.

Here's what I have problem with:

  1. I connect into DB.
  2. I get the current timestamp
  3. Every 10 seconds I want to print all elements added within this 10 seconds.
var timestamp = new Date().getTime();
  console.log('timestamp to compare: ' + timestamp);

setInterval(function() {
  var x = db.collection.find({'create_time' : {$gt : timestamp}}).toArray(function(err, entity) {
      console.log(entity);
  });

  console.log('checking...')
  timestamp = new Date().getTime();
  console.log('timestamp to compare: ' + timestamp);

}, 10000);

Somehow I'm getting no results. Below you can see the command prompt output. http://s11.postimg.org/a8cnffedf/2015_03_11_1521.png

I'll apreciate any help. Thank you.

Lelas
  • 73
  • 1
  • 7
  • Oh, between **var x** .... **console.log('checking...')** I put some code where I print the last document inside the collection. It's visible on the screen under attached url – Lelas Mar 11 '15 at 14:34
  • why dont you search for `current_timestamp - 10` something like: `timestamp = new Date().getTime() - (10 * 1000); var x = db.collection.find({'create_time' : {$gt : timestamp}}).toArray(function(err, entity) { console.log(entity); });` – darioguarascio Mar 11 '15 at 14:59
  • @Lelas are you storing timestamps inside Mongo as ISO strings or as integers? – Yuri Zarubin Mar 11 '15 at 15:05
  • ISO strings... I added quotes signs and now I received some results, however these are not entities added after time stored in the timestamp variable... does the timestamp has the right format? or maybe should be multiplied/divided by some value? – Lelas Mar 11 '15 at 15:19

1 Answers1

1

First, ensure that mongo recognizes the create_time property as a date. The easiest way to do that, is to insert standard javascript date instances:

db.collection.insert([{
    create_time: new Date(),
    ...
}], callback);

Then, to query, again use date instances:

var now = new Date();
var tenMinutesAgo = new Date(now - 10*60*1000);
db.collection.find({
    $gt: tenMinutesAgo
}).toArray(callback);

That should do the trick!

Jasper Woudenberg
  • 1,156
  • 9
  • 15
  • Ok I was able to solve it by simply changing the timestamp value inside the setInterval function. I use current timestamp and I should use timestamp decreased by 10 seconds. – Lelas Mar 13 '15 at 09:31