标签:ber ted localhost span nbu account 连接数据库 方法 --
连接数据库:参考地址:https://blog.oz-code.com/how-to-mongodb-in-c-part-2/
// Empty ctor will get you a // client with a default localhost and port #27017 MongoClient m = new MongoClient(); //---------------------------------------------------------------------- // Using a connection-string MongoClient m1 = new MongoClient("mongodb://localhost:27017"); //---------------------------------------------------------------------- // Using MongoClientSettings MongoClient client = new MongoClient( new MongoClientSettings { Server = new MongoServerAddress("localhost", 27018), // Giving 3 seconds for a MongoDB server to be up before we throw ServerSelectionTimeout = TimeSpan.FromSeconds(3) }); //---------------------------------------------------------------------- // Using MongoUrl MongoClient client1 = new MongoClient( MongoUrl.Create("mongodb://localhost:27017")); }
CURD:
MongoClient mongoClient = new MongoClient(configuration["DataBaseConnection:0:host"]); var dbAdmin = mongoClient.GetDatabase("shoppingMall"); var buyerCollection = dbAdmin.GetCollection<Buyer>("shoppingMall.buyer"); //新增 ////var a= buyerCollection.InsertOneAsync(new Buyer { buyerName="管理员", buyerAge=23, buyerAddress="江汉市天府大道067号", buyerSex=‘0‘, buyerIdCard="12355544884474", buyerHeadPortrait="~/images/admin.jpg", buyerAccountNumber="admin1" }); //查询 //linq写法 //var sql = from bb in buyerCollection.AsQueryable() // select bb; //sql= sql.Where(t => t.buyerAge >= 22); //var retlist = sql.ToList(); //ef写法 //var ret = buyerCollection.AsQueryable().GroupBy(t=>new { t.buyerAge }).Where(t=>t.Key.buyerAge>=22); //var b = ret.ToList(); var filterBuilder = Builders<Buyer>.Filter; var filter = filterBuilder.Gt("buyerAge", 10) & filterBuilder.Lt("counter", 30) & filterBuilder.Lt("counter", 30);//多个条件 //var filter = Builders<Buyer>.Filter.Gt("buyerAge", 1);//一个条件 var document = await buyerCollection.FindAsync(filter); var res = document.ToList(); //更新 var updateFilter = filterBuilder.Gt("buyerAge", 20) & filterBuilder.Lt("buyerAge", 30);//多个条件 var updated = Builders<Buyer>.Update.Set("buyerName", "李四"); var result = buyerCollection.UpdateManyAsync(updateFilter, updated).Result; //删除 var delFilter = filterBuilder.Gt("buyerAge", 20) & filterBuilder.Lt("buyerAge", 30);//多个条件 var resut = buyerCollection.DeleteManyAsync(delFilter).Result;
其中:
configuration["DataBaseConnection:0:host"]属于。netcore的连接字符串写法。具体实现如下:
appsettings.json:
"DataBaseConnection": [ { "host": "mongodb://localhost:27017" } ]
读取方法:
public IConfigurationRoot configuration; public BaseController() { //读取appsettings配置 var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); configuration = builder.Build(); }
标签:ber ted localhost span nbu account 连接数据库 方法 --
原文地址:https://www.cnblogs.com/llcdbk/p/9011672.html