1

Currently, I handle the created_at and updated_at fields myself, as part of the application logic.

I'm now using multi-document transactions for a bulk upsert: from the n documents specified, those which already exist in the collection are only updated, and those which doesn't, are inserted.

The problem is when an already existing document is updated, it's created_at field is updated too with the current date, which is incorrect for my business logic. If I don't specify a created_at field in this operation, then updated documents are fine, but the newly inserted ones are left without their creation time.

Having the driver/database itself deciding when to set both created_at and updated_at would be a solution since it is the driver/database itself who knows what kind of operation is being performed on each document.

With Node.js you can do the following:

schema.set('timestamps', true);

And createdAt and updatedAt fields will be automatically added to your schema and managed by mongo.

But I haven't been able to find something similar for the MongoDB Go Driver.

Has anyone done something similar?

Jairo Lozano
  • 3,883
  • 3
  • 20
  • 29
  • 1
    Use upsert, with $setOnInsert https://www.mongodb.com/docs/v4.4/reference/operator/update/setOnInsert/ for created_at field. – Alex Blex Jun 04 '22 at 00:49

0 Answers0