Getting server time in $setOnInsert using $currentDate?

Greetings, i have this database operation written in python using motor_asyncio

result = await collection.update_one({"ssid": ssid}, {
    "$addToSet": {"routes": route},
    "$setOnInsert": {"timestamps.added": datetime.utcnow()},
    "$currentDate": {"timestamps.last_modified": {"$type": "date"}}
}, upsert=True)

the issue i have with this is that id like to also get $currentDate in $setOnInsert
sadly doing "$setOnInsert": {"$currentDate": {"timestamps.added": True}} doesn’t really work.
This works fine as it is but im storing two different server times when using datetime.utcnow()

I would be grateful for hints or help, i did look into the docs but didint really find a solution

I see two options:

  1. Use $currentDate within $setOnInsert to have the server create the datetime for both fields.
  2. Don’t use $currentDate in either case, instead create the datetime in python and provide it for both fields.

Do either of these options work?

1 Like

I went with option 2

"$setOnInsert": {"timestamps.added": datetime.utcnow()},
"$set": {"timestamps.last_modified": datetime.utcnow()}

but im curious how would option 1 look, can you give an example?

@Shane could you show us how option 1 would look?

In a distributed system you really want to use the timestamp from the database, instead of each worker node as the clock could drift between those.

I also would like to use $currentDate with $setOnInsert (using the C# driver), but I suspect that this isn’t possible.
Can someone confirm that or give an example on how this can be done?