Get the time information from MongoDB's ObjectId

  • 2020-06-15 10:26:28
  • OfStack

By default, MongoDB USES the _id field as the primary key, of type ObjectId. There are 1 rules for ObjectId generation. See this article - MongoDB's ObjectId for more details. If you forget to write the creation time while writing to the database, don't worry, you can use the value of the _id field to restore the time. Check out the mongodb script script below:


db.getCollection('fees').find({}).forEach(function(item){
  var _str = item._id.toString().substr(10, 8);
  var _date = new Date(Number(parseInt(_str, 16).toString() + '000'));
  item.createTime = _date;
  db.fees.save(item);
})

forEach can iterate through every single piece of data in collection and make changes one by one. item._id.toString() will take the whole ObjectId("..." ), and then starting at the tenth character, take eight characters, and get the timestamp (with no millisecond bits) at the time the data was created. Add the millisecond digit "000" and construct the time object using the Date() method, assigning the createTime attribute.


Related articles: