mongodb在C#的连接以及curd写法

时间:2024-10-11 16:03:08

连接数据库:参考地址: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", ),
// Giving 3 seconds for a MongoDB server to be up before we throw
ServerSelectionTimeout = TimeSpan.FromSeconds()
});
//----------------------------------------------------------------------
// 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", ) & filterBuilder.Lt("counter", ) & filterBuilder.Lt("counter", );//多个条件 //var filter = Builders<Buyer>.Filter.Gt("buyerAge", 1);//一个条件
var document = await buyerCollection.FindAsync(filter);
var res = document.ToList(); //更新
var updateFilter = filterBuilder.Gt("buyerAge", ) & filterBuilder.Lt("buyerAge", );//多个条件 var updated = Builders<Buyer>.Update.Set("buyerName", "李四");
var result = buyerCollection.UpdateManyAsync(updateFilter, updated).Result; //删除
var delFilter = filterBuilder.Gt("buyerAge", ) & filterBuilder.Lt("buyerAge", );//多个条件 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();
}

其中,更新多个字段和查询指定字段()投影)的写法:

 //var filter = Builders<Buyer>.Filter.Gt("buyerAge", 1);//一个条件
var document = buyerCollection.Find(filter).Project(x=>new {buyerAddress=x.buyerAddress,buyerAge=x.buyerAge });//指定字段
var res = document.ToList(); ////更新
//var updateFilter = filterBuilder.Gt("buyerAge", 20) & filterBuilder.Lt("buyerAge", 50);//多个条件 //var updated = Builders<Buyer>.Update.Set("buyerName", "李四").Set("buyerAge", 12);//更新多个
  var result = await collection.FindOneAndUpdateAsync(
Builders<BsonDocument>.Filter.Eq("MasterID", ),
Builders<BsonDocument>.Update.Set("MasterID", )
);