c# MongoDB 驱动程序:FindOneAndUpdate 如何知道它是否找到了一个文档?

alb*_*ert 1 c# mongodb

因此,如果对象存在,我将使用 MongoDB 驱动程序更新数据库中的对象字段值。

 IMongoDatabase db = _mongoClient.GetDatabase(DataBase);
 IMongoCollection<Evento> collection = db.GetCollection<Evento>(str_collection);

 collection.FindOneAndUpdate(
     e => e._id == eventoId &&
     e._visitantes.Any(v => v._empresa == empresa &&
         v._nombre == nombre &&
         v._apellidos == apellidos),
     Builders<Evento>.Update.Set(e => e._visitantes[-1]._asistido, true));
Run Code Online (Sandbox Code Playgroud)

我的问题是:我怎么知道在数据库中找到了对象?我看过文档,但没有找到任何东西。

在它不存在的情况下,我不想创建一个新对象,只是我想知道一个对象是否发现改变了值。

谢谢。

Kir*_*kin 11

FindOneAndUpdate将返回一个文件。您可以使用 的ReturnDocument属性配置这是文档的旧版本还是更新版本FindOneAndUpdateOptions。设置ReturnDocumentReturnDocument.Before确保返回的文档是更新存在的文档,null如果不存在文档,则为该文档。下面是一个例子:

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.
}
Run Code Online (Sandbox Code Playgroud)