1

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:

ROKIKOKI
  • 571
  • 2
  • 9
  • 24
  • You can simply return the last documents sorted by your timestamp: `db.collection.find().sort({ timestamp: -1 }).limit(n)` such that `timestamp` is your date object and `n` is the number of documents you wish to return. – qsi Oct 22 '18 at 13:18
  • Yes but how do I extract timestamp of it? I tried: lastDoc = db.collection.find().sort({ timestamp: -1 }).limit(n); let docID = lastDoc._id; (undefined) timestamp = docID.getTimestamp(); (err) – ROKIKOKI Oct 22 '18 at 13:31
  • Note that `find()` returns a cursor, so you will naturally iterate through the result (e.g. get the last 10 timestamps) or use`lastDoc[0]` from your example. If you only need a single document, use `findOne()` instead. This will return a single document. So your code will look like this: `const lastDoc = db.collection.findOne().sort({ timestamp: -1 }); const docId = lastDoc._id; const lastTimestamp = lastDoc.timestamp; ...` – qsi Oct 23 '18 at 16:38

2 Answers2

5

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.

Rishabh Agarwal
  • 1,988
  • 1
  • 16
  • 33
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

Rishabh Agarwal
  • 1,988
  • 1
  • 16
  • 33
Tushar
  • 13
  • 4