MongoDB stores created timestamp in primary key field _id ObjectId. This field is indexed.
I need to store and filter documents by date (not created date) and I would like take advantage of this field.
How can I generate unique ObjectIds with my custom date? Should I do it? Or should I just create another field for my date and index it.
For the people looking to create a new mongo objectId for a custom timestamp, use the following for mongoose library
const mongoose = require('mongoose');
let anyTimeInMillisecs = Date.now();
var thisTimeStamp = Math.floor(anyTimeInMillisecs / 1000);
var newObjId = new mongoose.Types.ObjectId(thisTimeStamp); //our custom object ID
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With