C# 一秒看懂 MongDb.Driver的 UpdateReault 参数详解

UpdateReault参数解析


        //
        // 摘要:
        //     Gets a value indicating whether the result is acknowledged.
        public abstract bool IsAcknowledged { get; } //标识Update操作是否被确认 及update有没有成功
        //
        // 摘要:
        //     Gets a value indicating whether the modified count is available.
        //
        // 言论:
        //     The available modified count.
        public abstract bool IsModifiedCountAvailable { get; }//标识update操作是否进行了计数  如果IsAcknowledged&&IsModifiedCountAvailable--更新成功且可获取更新条数;如果 IsAcknowledged&&!IsModifiedCountAvailable--更新成功 但是无法获取更新条数 【该结果仅有驱动程序返回 只读】
        //
        // 摘要:
        //     Gets the matched count. If IsAcknowledged is false, this will throw an exception.
        public abstract long MatchedCount { get; }
        //
        // 摘要:
        //     Gets the modified count. If IsAcknowledged is false, this will throw an exception.
        public abstract long ModifiedCount { get; }
        //
        // 摘要:
        //     Gets the upserted id, if one exists. If IsAcknowledged is false, this will throw
        //     an exception.
        public abstract BsonValue UpsertedId { get; }//更新对象不存在 就会新增一条 该属性返回新增数据的_id

Mongdb.Driver对于 UpdateResult(abstract)有两种实现 Acknowledged 和 Unacknowledged

都是WriteConcern的其中一种级别 两者的区别在于 是否需要等待服务器响应 确认操作是否成功

Acknowledged

向数据库发送请求后,会阻塞等待数据库响应,确认操作最终结果

var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("sample");

// 将 WriteConcern 设置为 Unacknowledged 级别
var writeConcern = new WriteConcern(0);

// 插入数据并使用 Unacknowledged 级别
collection.InsertOne(new BsonDocument("name", "John Doe"));
Unacknowledged

向数据库发送请求后,不阻塞 不等待数据库响应 【当无需对操作结果进行检查 该种方式可以提高性能】

var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("sample");

// 将 WriteConcern 设置为 Unacknowledged 级别
var writeConcern = new WriteConcern(0);

// 插入数据并使用 Unacknowledged 级别
collection.InsertOne(new BsonDocument("name", "John Doe"), new InsertOneOptions { WriteConcern = writeConcern });// WriteConcern = writeConcern 将WriteConcern 设置为Unacknowledged 级别
posted @ 2023-03-15 11:05  C余L小R鱼  阅读(117)  评论(0编辑  收藏  举报