因此,如果对象存在,我将使用 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));
我的问题是:我怎么知道在数据库中找到了对象?我看过文档,但没有找到任何东西。
在不存在的情况下,我不想创建一个新的对象,只想知道一个对象有没有发现改变值。
谢谢。
最佳答案
FindOneAndUpdate
将返回一个文档。您可以使用 ReturnDocument
配置这是文档的旧版本还是更新版本FindOneAndUpdateOptions
的属性(property).将 ReturnDocument
设置为 ReturnDocument.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.
}
关于c# MongoDB 驱动程序 : FindOneAndUpdate how to know if it has found a document?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46215483/