Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom date in MongoDB ObjectId

Tags:

mongodb

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.

like image 767
user3287183 Avatar asked Aug 02 '26 07:08

user3287183


1 Answers

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
like image 169
Moh .S Avatar answered Aug 04 '26 09:08

Moh .S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!