简体   繁体   中英

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM