How to extract timestamp from MongoDB object

Asked
Active3 hr before
Viewed126 times

7 Answers

timestampextractmongodb
90%

In my php app, I do a db query that returns a bunch of documents from mongodb. As i'm looping through each document, i'm trying to extract the timestamp and display it as a Y-M-d h:i:s format. But I'm not even sure at this point how to extract it., How does the Bladesinging wizard's Extra Attack feature interact with the additional Attack action from the Haste spell? ,Object properties with numerical names need to be referenced as a string surrounded by curly braces:, Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers

Code looks like this:

$temp = $value->playbook_run_date->toDateTime();
echo ("<td>".$temp->format('r') ."</td>");
load more v
88%

Returns the timestamp portion of the ObjectId() as a Date.,The following example calls the getTimestamp() method on an ObjectId():,ObjectId.getTimestamp(),This will return the following output:

.leafygreen - ui - iokrs {
   color: inherit;font - size: 13 px;font - family: 'Source Code Pro',
   Menlo,
   monospace;line - height: 24 px;
}.leafygreen - ui - 1 v41da1 {
   border - spacing: 0;
   width: 100 % ;
}.leafygreen - ui - 7 razhx {
   border - spacing: 0;
   vertical - align: top;
   padding: 0 16 px;
}
ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp()
load more v
72%

Did you know that each MongoDB ObjectId contains an embedded timestamp of its creation time?,From the mongo shell, you can use getTimestamp() to retrieve the timestamp from the ObjectId, but there's no built in function to generate an ObjectId from a timestamp.,This online converter will convert from timestamp to ObjectId and vice versa.

e.g. to find all comments created after 2013-11-01:

db.comments.find({
   _id: {
      $gt: ObjectId("5272e0f00000000000000000")
   }
})
load more v
65%

Learn how to convert MongoIn any database, either Relational or NOSQL db, in a table/collection, there is a primary key for each row/document which is always unique. In MongoDB it’s ObjectId. ObjectId is a 12 byte value which consists of 4 bytes of creation time in seconds, 5 bytes of random value and 3 bytes of counter.,When you are working with mongo documents, sometimes you just want to create ObjectId from timestamps for querying through the collection. You can easily convert ObjectId to Timestamp and timestamp to ObjectId using the following code in JavaScript. Thanks to Steve Ridout, this looks so simple!, Save my name, email, and website in this browser for the next time I comment.,There’s another similar solution developed by Kumar Harsh.

var objectIdFromDate = function(date) {
   return Math.floor(date.getTime() / 1000).toString(16) + "0000000000000000";
};

var dateFromObjectId = function(objectId) {
   return new Date(parseInt(objectId.substring(0, 8), 16) * 1000);
};
75%

Is there a way to to exstract the timestamp from ObjectID with a simple json query that mongodump accepts?,I want to extract the timestamp from my ObjectID with a json query, as I would like to use mongodump but only dump data between certain dates. I dont wanna put my timestamps somewhere else than the ObjectID as I need the database to be as small as possible.,So is extracting some characters at a defined position:,For example, if you want to set the created timestamp to the current time, you could get a unix timestamp from the command line (which will be seconds since the epoch):

You can do this fairly simply, at doc page Mongo Extended JSON (which is quite well hidden) you can find a table describing how to represent mongo extended datatypes in JSON. As you probably know, the first 4 bytes of ObjectId represent the timestamp, this maps directly to 8 first characters in the hex string. Thus, the following should work:

jhonkola @ubuntu: ~$ mongoexport - d so_test - c example - q '{"_id" : {"$gt" : {"$oid" : "4fad36290000000000000000"}}}'
connected to: 127.0 .0 .1 {
   "_id": {
      "$oid": "4fad3629a8bbba98829d5c1e"
   },
   "a": "bar",
   "b": 2
} {
   "_id": {
      "$oid": "4fad362ea8bbba98829d5c1f"
   },
   "a": "baz",
   "b": 3
} {
   "_id": {
      "$oid": "4fad3635a8bbba98829d5c20"
   },
   "a": "buzz",
   "b": 4
} {
   "_id": {
      "$oid": "4fad363ca8bbba98829d5c21"
   },
   "a": "fizz",
   "b": 5
}
exported 4 records
jhonkola @ubuntu: ~$

Below are all the commands used for the example for reference.

> use so_test
switched to db so_test
   >
   db.example.insert({
      a: "foo",
      b: 1
   }) >
   db.example.insert({
      a: "bar",
      b: 2
   }) >
   db.example.insert({
      a: "baz",
      b: 3
   }) >
   db.example.insert({
      a: "buzz",
      b: 4
   }) >
   db.example.insert({
      a: "fizz",
      b: 5
   }) >
   db.example.find() {
      "_id": ObjectId("4fad3620a8bbba98829d5c1d"),
      "a": "foo",
      "b": 1
   } {
      "_id": ObjectId("4fad3629a8bbba98829d5c1e"),
      "a": "bar",
      "b": 2
   } {
      "_id": ObjectId("4fad362ea8bbba98829d5c1f"),
      "a": "baz",
      "b": 3
   } {
      "_id": ObjectId("4fad3635a8bbba98829d5c20"),
      "a": "buzz",
      "b": 4
   } {
      "_id": ObjectId("4fad363ca8bbba98829d5c21"),
      "a": "fizz",
      "b": 5
   } >
   db.example.find({
      _id: {
         $gt: ObjectId("4fad362e0000000000000000")
      }
   }) {
      "_id": ObjectId("4fad362ea8bbba98829d5c1f"),
      "a": "baz",
      "b": 3
   } {
      "_id": ObjectId("4fad3635a8bbba98829d5c20"),
      "a": "buzz",
      "b": 4
   } {
      "_id": ObjectId("4fad363ca8bbba98829d5c21"),
      "a": "fizz",
      "b": 5
   } >
   bye

jhonkola @ubuntu: ~$ mongodump - d so_test - c example - q '{"_id" : {"$gt" : {"$oid" : "4fad36290000000000000000"}}}'
connected to: 127.0 .0 .1
DATABASE: so_test to dump / so_test
so_test.example to dump / so_test / example.bson
4 objects

jhonkola @ubuntu: ~$ mongoexport - d so_test - c example - q '{"_id" : {"$gt" : {"$oid" : "4fad36290000000000000000"}}}'
connected to: 127.0 .0 .1 {
   "_id": {
      "$oid": "4fad3629a8bbba98829d5c1e"
   },
   "a": "bar",
   "b": 2
} {
   "_id": {
      "$oid": "4fad362ea8bbba98829d5c1f"
   },
   "a": "baz",
   "b": 3
} {
   "_id": {
      "$oid": "4fad3635a8bbba98829d5c20"
   },
   "a": "buzz",
   "b": 4
} {
   "_id": {
      "$oid": "4fad363ca8bbba98829d5c21"
   },
   "a": "fizz",
   "b": 5
}
exported 4 records
load more v
40%

The timestamp component of an ObjectId is its most significant 32 bits, which denotes the number of seconds since the Unix epoch. This value is read as an unsigned 32-bit integer with big-endian byte order. , Returns the timestamp component of this ObjectId. ,MongoDB\BSON\ObjectId::getTimestamp — Returns the timestamp component of this ObjectId,Note: Because PHP's integer type is signed, some values returned by this method may appear as negative integers on 32-bit platforms. The "%u" formatter of sprintf() may be used to obtain a string representation of the unsigned decimal value.

integer(1484854719)
integer(42)
22%

You can use $convert function to extract the date from ObjectId starting in 4.0 version.,Yes you can query object by date using MongoDB inserted ID db.collectionname.find({_id: {$lt: ObjectId.fromDate( new ISODate("TZformat") ) } });,In rails mongoid you can query using,You can query on date comparing between start and end time for date.

Briefly in JavaScript code:

/* This function returns an ObjectId embedded with a given datetime */
/* Accepts both Date object and string input */

function objectIdWithTimestamp(timestamp) {
   /* Convert string date to Date object (otherwise assume timestamp is a date) */
   if (typeof(timestamp) == 'string') {
      timestamp = new Date(timestamp);
   }

   /* Convert date object to hex seconds since Unix epoch */
   var hexSeconds = Math.floor(timestamp / 1000).toString(16);

   /* Create an ObjectId with that hex timestamp */
   var constructedObjectId = ObjectId(hexSeconds + "0000000000000000");

   return constructedObjectId
}

/* Find all documents created after midnight on May 25th, 1980 */
db.mycollection.find({
   _id: {
      $gt: objectIdWithTimestamp('1980/05/25')
   }
});
load more v

Other "timestamp-extract" queries related to "How to extract timestamp from MongoDB object"