Home > Mobile >  Adding createdAt and updatedAt in pymongo
Adding createdAt and updatedAt in pymongo

Time:08-30

I want to add auto generated field created_at and updated_at in mongodb in python using pymongo.

This functionality is provided in Javascript when creating mongo schema using

var yourSchema = new Schema({..}, { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at'} });

How exactly can this be done in pymongo?

CodePudding user response:

This is a mongoose feature, not to be confused with javascript or MongoDB. pymongo does not offer such capabilities.

You will just have to manually specify them in your operations, for example:

from datetime import datetime

db.collection.updateOne({
   "key": 5
},
{
  "$set": { "updated_at": datetime.now() },
  "$setOnInsert": { "created_at": datetime.now() }
}, upsert=True)
  • Related