MongoDB.Driver c# 操作

读取

       List<string> getfolderGuidList()
       {
           var folderGuidList = new List<string>();
           try
           {
               // 读取连接字符串
    var   strCon = $"mongodb://{userName}:{PassWord}@{ip}:{port}/{dbName}";
               var mongoUrl = new MongoUrlBuilder(strCon);
               // 创建并实例化客户端
               var _client = new MongoClient(mongoUrl.ToMongoUrl());
               //  根据数据库名称实例化数据库
               var database = _client.GetDatabase(dbName);
               var tbName = "folder";
               var collection = database.GetCollection<BsonDocument>(tbName);
               var filterBuilder = Builders<BsonDocument>.Filter;
               var filter = filterBuilder.Eq("folderType", 1);
               var list = collection.Find(filter).ToList();
               foreach (BsonDocument doc in list)
               {
                   folderGuidList.Add(doc["folderGuid"].ToString());
               }
           }
           catch (Exception e)
           {
               Log(e, "err");
            }

            return folderGuidList;
       }
读取列表

查找

等于

var filterBuilder = Builders<BsonDocument>.Filter;
var filter = filterBuilder.Eq("folderType", 1);

存在某字段

filterBuilder.Exists("program",true)

.Exists("programs.0", true); 数组的第一个元素存在

包含

var GuidList = new List<string>();
var filter = Builders<BsonDocument>.Filter.In("Guid", GuidList);

 

修改
var result = collection.UpdateMany(filter,mUpdateDocument);
delNum = result.ModifiedCount;

删除

var result = collection.DeleteMany(filter);
var delNum= result.DeletedCount;

posted @ 2023-01-11 17:25  simadi  阅读(133)  评论(0编辑  收藏  举报