Deep into Obtaining Time Information from MongoDB’s ObjectId

Time:2019-9-7

MongoDB defaults to using the _id field as the primary key, with the type ObjectId. There are certain rules for generating ObjectId, and you can see this article for more details – ObjectId in MongoDB. If you forget to write the creation time when you write to the database, don’t worry, you can restore the time by the value of the _id field. Look at the following mongodb script script:


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 traverse each piece of data in the collection and then modify it one by one. Item. _id. toString () treats the entire ObjectId (“…”) as a string, and then takes eight characters from the tenth character to get the timestamp (without milliseconds) when the data is created. After that, the number of millisecond digits “000” is added, and then the time object is constructed by Date () method and assigned to the createTime attribute.

Above mentioned is a brief introduction to you about how to get time information from ObjectId of MongoDB. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to developpaer.

Recommended Today

Deeply analyze the principle and practice of RSA key

1、 Preface After experiencing many dark moments in life, when you read this article, you will regret and even be angry: why didn’t you write this article earlier?! Your darkest moments include: 1. Your project needs to be connected with the bank, and the other party needs you to provide an encryption certificate. You have […]