So I\'m using the MongoDB driver to update an object field value in the database if the object exist.
IMongoDatabase db = _mongoClient.GetDatabase(DataBase);
I
The mongoose documentation states in the Options section:
Options:
- ...
- upsert: bool - creates the object if it doesn't exist. defaults to false.
- ...
There should an upsert
parameter, which, if set to true, will create a new object if none was found. However, this defaults to false, so your call should not create a new database entry.
I would assume that the C# driver
should behave identically. If not, you could set the Upsert
parameter to false, see here
FindOneAndUpdate will return a document. You can configure whether this is the old or the updated version of the document by using the ReturnDocument property of FindOneAndUpdateOptions. Setting ReturnDocument
to ReturnDocument.Before
ensures that the document that gets returned is the document that existed before the update, which would be null
if no document existed. Here's an example:
var documentBefore = collection.FindOneAndUpdate(
filterDefinition,
updateDefinition,
new FindOneAndUpdateOptions { ReturnDocument = ReturnDocument.Before });
if (documentBefore != null)
{
// The document already existed and was updated.
}
else
{
// The document did not exist and was inserted.
}