因此,如果对象存在,我正在使用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
将返回文档。您可以使用FindOneAndUpdateOptions
的ReturnDocument
属性来配置该文档的旧版本还是更新版本。将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.
}
options 部分中的Mongoose文档状态:
选项:
- ...
- upsert:bool-如果对象不存在,则创建该对象。默认为false。
- ...
应该有一个upsert
参数,如果设置为true,如果没有找到新对象。但是,此默认为false,因此您的调用不应创建新的数据库条目。
我假设C# driver
的行为应相同。如果不是,则可以将Upsert
参数设置为false,请参阅此处