Mongodb: How to Get Timestamp and Objectid from Newest Document in Collection?

I would like to get last created documents in collection and return their objectID and timestamps. For example if yesterday I created 10 documents I would like to return them with db.collection and then

const lastTimeStamp = will be the timestamp from the last created element

const lastTimeStampArray = will be array of timestamps from yesterdays records

const lastObjectId = will be ObjectID of last created document

const lastObjectIdsArray = array of last objectIds

I am using:

3

2 Answers

MongoDB's _id field has info about date stored in itself. The timestamp is contained in the first 4 bytes of a mongoDB id.

  • You can use ObjectId.getTimestamp() function to get time from _id of a document.
  • Sorting on an _id field that stores ObjectId values is roughly equivalent to sorting by creation time.

For you question:

// To get lastTimeStamp
db.collection.find().sort({ '_id': -1}).limit(1).forEach( 
   function(doc){ 
      lastTimeStamp = doc._id.getTimestamp(); 
   }
)


// to get lastObjectId
db.collection.find().sort({ '_id': -1}).limit(1).forEach( 
   function(doc){ 
       lastObjectId = doc._id; 
   }
)

Now, to get all records inserted yesterday might be a bit of hard work. You need to extract all records inserted yesterday and from that you need to extract information you need.

// to get lastTimeStampArray and lastObjectIdsArray
var yesterdayStart = new Date();
yesterdayStart.setDate(yesterdayStart.getDate() - 1);
yesterdayStart.setHours(0,0,0,0);
var startId = Math.floor(yesterdayStart.getTime() / 1000).toString(16) + "0000000000000000";

var yesterdayEnd = new Date();
yesterdayEnd.setDate(yesterdayEnd.getDate() - 1);
yesterdayEnd.setHours(23,59,59,999);
var endId = Math.floor(yesterdayEnd.getTime() / 1000).toString(16) + "0000000000000000";

var lastTimeStampArray = [];
var lastObjectIdsArray = [];

db.collection("records")
   .find( { _id: { 
                $gte: ObjectId(startId),
                $lte: ObjectId(endId)
              } 
       }
).forEach(
     function(doc){
         lastObjectIdsArray.push(doc._id);
         lastTimeStampArray.push(doc._id.getTimestamp());
});

These are mongo shell commands you can write your node.js accordingly.

1

You can get last inserted record with timestamp using the following:

db.collection.find().sort({ '_id': -1 }).limit(1).forEach(
     function(doc){
         print("record:"+doc._id.getTimestamp());
})

_id is the Mongodb objectID

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest