Search code examples
mongodbspring-data-mongodbmongotemplatenosql

MongoDB get all documents that were created in the last 30 minutes from the _id field alone


I have a document with no "timeCreated" field. I would like to get all the entries from the last 30 minutes. Iv'e heard that the _id field contains the time created logic within it.

How can i do that?

thanks!


Solution

  • getTimestamp() will give you the date/time from the ObjectId.

    You can do the following

    var oldest = new Date(new Date() - new Date(30 * 60000));
    db.collection.find().sort({ _id: -1 }).forEach(function(item) {
      if (item._id.getTimestamp() > oldest){
         ...
      }
    });