Use time of the database server for a timestamp in a document

48 views
Skip to first unread message

javantamt

unread,
Nov 21, 2016, 7:45:26 PM11/21/16
to mongodb-user
Hey there,
is it possible to create a Value in a document with a client, which is replaced by the database server with the creation time?
Why should I need this?
I'm going to handle Jobs in a distributed system. Those systems may have different system times. But what matters for factoring the jobs is the time of creation, which is equal to the priority of the job.

{"timestamp":"$magicTimeExpression"}

thx javantamt

Kevin Adistambha

unread,
Nov 28, 2016, 12:29:22 AM11/28/16
to mongodb-user

Hi,

is it possible to create a Value in a document with a client, which is replaced by the database server with the creation time?

I believe you’re looking for the $currentDate operator.

Please note that $currentDate is an update operator. You can use the upsert option if you need to insert a new document instead.

Best regards,
Kevin

javantamt

unread,
Nov 30, 2016, 5:28:26 PM11/30/16
to mongodb-user
Thank you,
it looks like the answer I was looking for.
I need both, the updating and the creating of a new document.

I've a problem with the updating a non existing document. Which key/value combination should I put into the find-options to be sure that this does not fit any existing document?
I could search for something like { "MagicProbablyNeverExisting123Key":"9.75"} but is there a nicer probably more performance way in doing it?

thx
javantamt


Kevin Adistambha

unread,
Dec 6, 2016, 5:27:35 PM12/6/16
to mongodb-user

Hi javantamt

Which key/value combination should I put into the find-options to be sure that this does not fit any existing document?

This would depend on your schema design and your data. The most straightforward method is to use the _id field as the search key for the update query, since MongoDB requires the _id field to be unique, and also creates an index on it automatically. If you have a unique identifier of some kind that exists for all your documents (e.g. UUID or some other identifier specific to your data), then you may be able to use that identifier as the _id field.

For example, if you have a unique key of 1234, the command:

db.collection.update({_id:1234}, {$currentDate: {...}, $set: {...}}, {upsert: true})

will create a new document with the specified _id field if a document with that _id doesn’t exist.

Best regards,
Kevin

javantamt

unread,
Jun 15, 2017, 8:37:08 AM6/15/17
to mongodb-user
Sry, I lost track of the discussion. Thank you for you help, it was what I was looking for!
Reply all
Reply to author
Forward
0 new messages