如何使用C# 对MongoDB数据库操作
一、在nuget 引入MongoDB.Bson,和MongoDB.Driver这个两个类库
二、对MongoDB数据库连接
string con = @"mongodb://127.0.0.1:27017"; var client = new MongoClient(con); //数据库 var database = client.GetDatabase("test");
三、连接MongoDB集合
IMongoCollection<BsonDocument> mongoCollection = database.GetCollection<BsonDocument>("userInfo");
四、查询集合的所有数据
Console.WriteLine("--------查询所有----------"); var res = mongoCollection.Find(new BsonDocument()).ToList(); foreach (var item in res) { Console.WriteLine(item); } //使用多线程查询所有数据 var list = Task.Run(async () => await mongoCollection.Find(new BsonDocument()).ToListAsync()).Result; list.ForEach(p=>{ Console.WriteLine("编号:"+p["id"]+", 姓名:"+p["name"]+",性别:"+p["sex"]+",地址:"+p["address"]); });
条件查询
var res = arti.Find(new BsonDocument() { { "stuName", "李四" } }).ToList(); foreach (var item in res) { Console.WriteLine(item); }
排序
Console.WriteLine("-------------升序-------------"); var stort_asc = Builders<BsonDocument>.Sort.Ascending("id"); Console.WriteLine("-------------降序----------------"); var stort_desc = Builders<BsonDocument>.Sort.Descending("id");
查询已经排序的的数据
Console.WriteLine("--------------条件判断--------------"); var sort_ascending = Builders<BsonDocument>.Sort.Ascending("id"); //根据id升序 var sort_descending = Builders<BsonDocument>.Sort.Descending("id"); //根据id降序 var res_c = mongoCollection.Find(Builders<BsonDocument>.Filter.Lt("id", 30) & Builders<BsonDocument>.Filter.Gte("id", 1)).Limit(50).Sort(sort_descending).ToCursor(); //查询id小于10,大于2的数据 foreach (var item in res_c.ToEnumerable()) { Console.WriteLine(item); }
添加数据
var add = new BsonDocument { { "id", 15 }, { "name", "王二" }, { "sex", "女" }, { "address", "三墩" } }; mongoCollection.InsertOne(add);
更新数据
var update = mongoCollection.UpdateMany(Builders<BsonDocument>.Filter.Eq("id", 13),Builders<BsonDocument>.Update.Set("name","李世民"));
删除数据
//根据条件删除 mongoCollection.DeleteOne(Builders<BsonDocument>.Filter.Eq("id", 13));