Reputation: 621
Question in short: Is there anyway to automatically add createdAt
field to each document inserted in a collection in MongoDB?
Scenario: I'm using a dockerized instance of MongoDB and I want to automatically add createdAt
field to every document on insertion. I want to achieve this using MongoDB itself because the database can have multiple input channels like Logstash, Python code, ..etc.
Note: I should be able to execute JavaScript code using init file in docker-entrypoint-initdb.d
.
Is there a hook or something I can use to automatically achieve this ?
Upvotes: 6
Views: 7180
Reputation: 10697
Natively the createdAt timestamp is contained inside the first 4 bytes in the default mongoDB _id field in newly inserted document , so generally you dont need one more field that will contain same data:
> db.yourCollection.findOne()._id.getTimestamp()
ISODate("2022-05-05T02:57:31Z")
But modern frameworks add this option so for example in node.js you can add something like this:
var yourSchema = new Schema({..});
yourSchema.set('timestamps', true);
which will add the "createdAt" and "updatedAt" fields to the document automatically on insert or update operations via the framework... or if you need only createdAt:
var yourSchema = new Schema({..}, { timestamps: { createdAt: 'created_at' } });
There is also an option called $setOnInsert where you can add the createdAt during upsert operation:
db.yourCollection.updateOne(
{ _id: 1 },
{
$set: { item: "Some item" },
$setOnInsert: { createdAt: new Date() }
},
{ upsert: true }
)
Upvotes: 7