Lelas
Lelas

Reputation: 73

Find document by timestamp using mongojs

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.

Upvotes: 1

Views: 407

Answers (1)

Jasper Woudenberg
Jasper Woudenberg

Reputation: 1166

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!

Upvotes: 1

Related Questions