c#MongoDB驱动程序:FindOneAndUpdate如何知道它是否已找到文档? [英] c# MongoDB driver: FindOneAndUpdate how to know if it has found a document?

查看:688
本文介绍了c#MongoDB驱动程序:FindOneAndUpdate如何知道它是否已找到文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,如果对象存在,那么我正在使用MongoDB驱动程序来更新数据库中的对象字段值.

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);
 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));

我的问题是:我如何知道该对象已在数据库中找到?我已经看过文档,但没有发现任何东西.

My question is: how I know that the object has found in the database? I have seen the documentation and I didn't found anything.

在不存在该对象的情况下,我不想创建一个新对象,只想知道是否找到了一个可以更改值的对象.

In the case it doesn't exist, I don't want to create a new object, only I want to know if an object has found to change the value.

谢谢.

推荐答案

ReturnDocument 属性noreferrer> FindOneAndUpdateOptions .将ReturnDocument设置为ReturnDocument.Before可以确保返回的文档是更新之前之前存在的文档,如果不存在该文档,则为null.这是一个示例:

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.
}

这篇关于c#MongoDB驱动程序:FindOneAndUpdate如何知道它是否已找到文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆