十年河东,十年河西,莫欺少年穷
学无止境,精益求精
这篇博客本不打算写的,因为主要是代码,但之前的一篇博客幅度太长,所以,单独为更新单条记录写一篇吧。
之前mongdodb增删改查博客地址为:
更新单条数据思路如下:一步步操作mongoDB,增删改查,分页查询 C#
按照一定排序,找出单条记录,并根据这条记录的主键来构造过滤器,代码如下:
private void UpdateOta(string BatterySN) { LogstoreDatabaseSettings st_now = new LogstoreDatabaseSettings() { LogsCollectionName = CommEnum.BatteryOtaEnm.OtaRecords.ToString(), DatabaseName = DatabaseName }; var client = new MongoClient(st_now.ConnectionString); var database = client.GetDatabase(st_now.DatabaseName); var Mongo = database.GetCollection<OtaRecordsTb>(st_now.LogsCollectionName); var builder = Builders<OtaRecordsTb>.Filter; var filter = builder.Eq("BatterySN", BatterySN); //排序生成器 SortDefinitionBuilder<OtaRecordsTb> builderSort = Builders<OtaRecordsTb>.Sort; //排序约束 Ascending 正序 Descending 倒序 SortDefinition<OtaRecordsTb> sort = builderSort.Descending("CreateTime"); var MongoEntity = Mongo.Find(filter).Sort(sort).FirstOrDefault(); if (MongoEntity != null) { var Id = MongoEntity.Id; var filterId = builder.Eq("Id", Id);//通过ID 找到唯一记录 构建过滤器 这样就可以单独更新某一条数据了 var update = Builders<OtaRecordsTb>.Update.Set("IsSuccess", "升级成功"); Mongo.UpdateOne(filterId, update); } }