c# MongoDB driver: FindOneAndUpdate how to know if it has found a document?

前端 未结 2 870

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         


        
相关标签:
2条回答
  • 2021-01-26 20:53

    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

    0 讨论(0)
  • 2021-01-26 20:56

    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.
    }
    
    0 讨论(0)
提交回复
热议问题