Saving server-side Date on insert

Is there any way to insert a document with server-side Date, or some workaround for it?

1 Like

Hello @Noam_Gershi, Welcome to the MongoDB community forum,

Default ObjectId:

If you are using MongoDB’s default ObjectId in _id, that includes a timestamp component which you can use to infer the creation date for a document. you will find a method to get timestamps from the _id property in a specific language driver whatever you are using.

If it is still needed then you can try the below options:

Update Query Options:

There are other options to add timestamps in MongoDB server-side using update methods only,

1). $currentDate: you can use this operator with upsert: true option

Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. Fields with numeric names are processed in numeric order. See Update Operators Behavior for details.

Show Query
db.collection.updateOne(
  {
    // pass query that does not find any document
  },
  {
    $currentDate: {
      // date property, modify to whatever you want to set
      dateProperty: true
    },
    $set: {
      // your insert object properties
      // ...
    }
  },
  { upsert: true }
)

2). Aggregation Alternative to $currentDate: you can use “$$NOW” or “$$CLUSTER_TIME” with update with aggregation pipeline and upsert: true option

Starting in version 4.2, update methods can accept an aggregation pipeline. As such, the previous example can be rewritten as the following using the aggregation stage $set and the aggregation variables NOW (for the current datetime) and CLUSTER_TIME (for the current timestamp):

Show Query
db.collection.updateOne(
  {
    // pass query that does not find any document
  },
  [{
    $set: {
      // date property, modify to whatever you want to set
      dateProperty: "$$NOW",
      // your insert object properties
      // ...
    }
  }],
  { upsert: true }
)
1 Like

Thanx for the reply!

Since _id has seconds-precision, and not millis-precision (as with Date) - I wonder if it is safe to use instead MongoDB Timestamp type (which also has seconds-precision) . From MongoDB documentation:

The BSON timestamp type is for internal MongoDB use. For most cases, in application development, you will want to use the BSON date type.

  1. What’s the differences between using _id or Timestamp?
  2. Does the above citation means that we can use it since it could be changed/deprecated?
  3. Does there any performance differences between using those _id or Timestamp?
  4. When using _id - is it efficient to fetch all the _id between 2 given dates?

Hi @Noam_Gershi

Note that the timestamp type is intended to be used for internal MongoDB processes. You can of course try to use it if it fits your use case, but bear in mind the reason why this type is created.

Instead, it’s recommended to use the date type instead for most cases.

In general, although the default ObjectId type does contain a date information, if you need the dates to do some processing (e.g. fetching between two dates), then it’s usually better to have a field dedicated to storing this date. This way, you can use many aggregation operations on dates, such as $dateAdd, $dateDiff, $dateSubtract, $dateToParts, $dateToString, and others. Those are not available for ObjectId-derived dates.

Best regards
Kevin

4 Likes

Let’s say I want to add a new document with the lastUpdate field and I would also like to get the newly inserted _id, how can I do that? I know that I can just add the _id field for the insert, but is it possible to have two identical _id generated and cause one of the record being override?

You may want to create a new thread as opposed to resurrecting an old one. You’re not going to get a duplicate _id if you let the server / driver create it for you. If using straight shell and certain APIs you’ll get the created ID returned to you anyway:

You didn’t way what language you’re using so I can’t check any driver documentation for what you may want, but you can check yourself on the mongo driver docs pages: