Home > database >  How can I make a value in MongoDB only be set once?
How can I make a value in MongoDB only be set once?

Time:10-07

How can I check if a value exists on "timestamp", and if it doesn't exist I want it to update it but if the value exists I want it to leave it alone?

CodePudding user response:

First look for the value. If it doesn't exist create it, else do nothing.

CodePudding user response:

MongoDB has a field called _id. This field is special as it is the only field in mongo that is immutable. Also, this field is mandatory. If you do not specify a value it will default to a new ObjectId() value.

If this timestamp value you wish to save is actually the record creation date time then simply use the default ObjectId() value. The ObjectId is a special type that has an embedded timestamp value within it.

Here is how you would see the timestamp of an ObjectId() using the mongo shell...

MongoShell View Date and Time of ObjectId

var x = new ObjectId();
x.getTimestamp();

Results

> x.getTimestamp();
ISODate("2021-10-06T22:12:50Z")

Having this field an immutable field your primary objective is covered. You have a timestamp and a field that cannot be modified. The problem is having an undefined value for some period of time. I would need more clarity on how the record would not have a timestamp...

  • Related