Last active
March 8, 2020 10:44
-
-
Save robertdempsey/6e9e8e9181db84fb38e170ea07eb5bb2 to your computer and use it in GitHub Desktop.
Will set the property 'created_at' to the current date and time when an existing document is not found
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** create connection pool to system DB in MongoDB | |
* assume we are using https://www.npmjs.com/package/mongodb | |
* assume we start with no document with property matching 'system_id: 123' | |
*/ | |
system_states_collection.update( | |
{ system_id: 123 }, | |
{ | |
$set: { a: 4 }, | |
$setOnInsert: { created_at: new Date() } | |
}, | |
{ upsert: true } | |
) | |
/** | |
Resulting document: | |
{ | |
system_id: 123, | |
a: 4, | |
created_at: '2020-03-08T10:27:21.230Z' | |
} | |
*/ | |
system_states_collection.update( | |
{ system_id: 123 }, | |
{ | |
$set: { b: 5 }, | |
$setOnInsert: { created_at: new Date() } | |
}, | |
{ upsert: true } | |
) | |
/** | |
Resulting document: | |
{ | |
system_id: 123, | |
a: 4, | |
b: 5 | |
created_at: '2020-03-08T10:27:21.230Z' | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment