How to convert from Timestamp to Mongo ObjectID - mongodb

I know that we can use getTimestamp() to retrieve the timestamp from the ObjectId, but is there any way to generate an ObjectId from a timestamp?
More specifically, if I have an input of month and year, then I want to convert it into Mongo ObjectID to query in db, how should I do this?

try this,
> ObjectId("5a682326bf8380e6e6584ba5").getTimestamp()
ISODate("2018-01-24T06:09:42Z")
> ObjectId.fromDate(ISODate("2018-01-24T06:09:42Z"))
ObjectId("5a6823260000000000000000")
Works from mongo shell.

If you pass a number to the bson ObjectId constructor it will take that as a timestamp and pass it to the generate method.
You can get a Date from a month and year per this answer (months start at zero).
So:
timestamp = ~~(new Date(2016, 11, 17) / 1000)
new ObjectId(timestamp)

Yes you can:
dummy_id = ObjectId.from_datetime(gen_time)
Where gen_time is datetime.

An ObjectId() is a 12-byte BSON type and consists of:
The first 4 bytes representing the seconds since the unix epoch
The next 3 bytes are the machine identifier
The next 2 bytes consists of process id
The last 3 bytes are a random counter value
Clearly, you will not be able to create ObjectId() only from timestamp.

Related

How to query collection for documents created at a certain time range using the ObjectId field? [duplicate]

This question already has answers here:
Can I query MongoDB ObjectId by date?
(13 answers)
Closed 19 days ago.
I have a collection that has the default _id field, which stores the ObjecId which contains the timestamp of creation.
How do I write a query to find all docs created between MIN_DATE and MAX_DATE?
EDITED:
It must still be able to use the index.
You can compare ObjectId values using $lt and $gt.
Since we know that the first part of the ObjectId is the epoch timestamp, we can construct an ObjectId value that correspond to a specific time.
In mongosh that might look like:
> ObjectId((new Date("2022-03-01T00:00+0000").valueOf()/1000).toString(16) + "0000000000000000")
ObjectId("621d62000000000000000000")
That constructed value would be greater than any ObjectId created prior to the specified datetime (1 Mar 2022 midnight UTC in this case), and less than or equal to any ObjectId created during that second or after.
Once you contruct an ObjectId values for both dates of interest, query the collection similar to:
db.collection.find({_id:{$gte:olderObjectIdValue, $lt:newerObjectIdValue}})

Format the inserted date in MongoDB

how can we format the date when you insert it into a collection in MongoDB ?
db.collection('transactions').insertOne({
amount: 1,
id: req.params.userid,
date: new Date ()
})
I tried things like
new Date (<YYYY-mm-dd>)
new Date ("<YYYY-mm-dd>")
But it doesn't work.
Google isn't really helping either.
Thank you
It is not possible with Date type
Reference
new Date() returns the current date as a Date object. mongosh wraps the Date object with the ISODate helper. The ISODate is in
UTC
BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). This results in a representable date range of about 290 million years into the past and future.
On the other hand, you could do the below things
You can either use String type, but you need to convert to date before doing any queries
or
You need to convert to the desired format before returning to the client.

Mongo how to convert an ISO date to a BSON timestamp value

In Mongodb, if I have an ISODate of "2021-07-29T01:57:49.075Z", how do I convert this value to the equivalent BSON timestamp value? The BSON value should be in the form of Timestamp(nnnnnnnnnn, 1). The n value is 10 digits long. I've seen a close answer using the $toLong aggregate, but the long number returned doesn't fit into the 10 digits.
Also the reverse, how to convert a BSON timestamp value to an ISODate.
This seems so simple but I can't find any reference and similar questions convert to a long number not a BSON timestamp in the form described above.
Thanks for your help.

How to convert BSON Timestamp from Mongo changestream to a date in javascript?

I already have a SO question and answer on how to convert BSON Timestamp in a MongoDB aggregation, but now I have a situation where I would like to convert in node.js.
So just to repeat. My goal is to convert a "Timestamp" datatype to a javascript date, without doing it in an aggregation - is this possible?
If the BSON library you are using provides Timestamp type, you can use its getTime method to return the seconds, and create a date from that:
Date(object.clusterTime.getTime())
If you don't have that function available, the timestamp is a 64-bit value where the high 32-bits are the seconds since epoch, and the low 32-bits are a counter.
Bitshift the value 32 bits right or divide by 2^32 to get the seconds:
Date(object.clusterTime/Math.pow(2,32))

Algorithm for mongo objectid filed in mongodb and how to get last 24 hour data from mongo collection

Is there any way to get objectids that are genrated in last 24 hours in mongo collection based on time stamp on objectid and what is the algorithm to genrate objectid in mongodb .
Is there any way to get objectids that are genrated in last 24 hours in mongo collection based on time stamp on objectid
You can call JavaScript code such as:
date = new Date()
date.setDate(date.getDate() - 1)
yesterday = Math.floor(date.getTime()/1000).toString(16)
db.coll.find({_id : {$gt : new ObjectId(yesterday + "0000000000000000")}} , {_id:1})
The first and second statements are straightforward: yesterday's date.
Third row creates a 4-Byte Hex String of yesterday. Which are the 4 leftmost bytes of ObjectId.
Then, you pad the 8 rightmost bytes of the ObjectId with zero's as you don't care about those. These are mac address(3), pid(2) and a running counter(3)
All you have to now is query your collection (coll in the example) and return the _id's
what is the algorithm to genrate objectid in mongodb
There you are