- nuget
-
安裝 MongoDB.Driver(我操作版本2.10.0)
- 使用(封裝什么的這里就不寫了,直接寫最直接的使用)
2.1 連接字符串
- 修改文件 appsettings.Development.json | appsettings.json (開發(fā)環(huán)境|生產(chǎn)環(huán)境)
- 賬號(hào)訪問 (用戶名:密碼@連接的值/對(duì)映的數(shù)據(jù)庫(kù))
"MongoDatabaseSettings": {
"ConnectionString": "mongodb://name:password@localhost:27018/myDB",
"DatabaseName": "myDB"
},
- 直接訪問
"MongoDatabaseSettings": {
"ConnectionString": "mongodb://localhost:27018",
"DatabaseName": "myDB"
},
2.2 創(chuàng)建連接字Model MongoSettings.cs
public class MongoDatabaseSettings : IMongoDatabaseSettings
{
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
public interface IMongoDatabaseSettings
{
string ConnectionString { get; set; }
string DatabaseName { get; set; }
}
2.3 創(chuàng)建MongodbService.cs
public class MongodbService
{
// 管理員集合
public AdminService AdminsCollection;
// 用戶集合
public UserService UserCollection;
// 數(shù)據(jù)庫(kù)
public IMongoDatabase Database { get; set; }
public MongodbService(IMongoDatabaseSettings settings)
{
// 創(chuàng)建連接
var client = new MongoClient(settings.ConnectionString);
// 獲取數(shù)據(jù)庫(kù)
Database = client.GetDatabase(settings.DatabaseName);
// 獲取文檔
AdminsCollection = new AdminService(GetCollection<Admin>("admins"));
UserCollection = new UserService(GetCollection<User>("users"));
}
// 獲取文檔
private IMongoCollection<T> GetCollection<T>(string name) => Database.GetCollection<T>(name);
}
2.4 注入 Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// 獲取配置文件 的 MongoSettings
services.Configure<MongoSettings>(
Configuration.GetSection(nameof(MongoSettings)));
// 注入連接字符串
services.AddSingleton<IMongoDatabaseSettings>(sp =>
sp.GetRequiredService<IOptions<MongoSettings>>().Value);
// 注入MongodbService
services.AddSingleton<MongodbService>();
services.AddControllers();
}
2.5 collertion 中使用
- 構(gòu)造函數(shù)中注入 MogodbService
- 就可以使用 MogodbService 中的對(duì)象了
public class LoginController : Controller
{
private AdminService _adminCollection;
private MongodbService _mongodbService;
public LoginController(MongodbService mongodbService)
{
_mongodbService = mongodbService;
_adminCollection = mongodbService.AdminsCollection;
}
}
我覺得很實(shí)用的兩個(gè)方法
- 構(gòu)造過濾器 (偽代碼)
var filter = Builders<T>.Filter.Where(T => T.xx == xx && T.xxx = xxx);
var data = Collection.Find(filter);
- 字段映射(偽代碼)
var filter = Builders<T>.Filter.Where(T => T.xx == xx && T.xxx = xxx);
var projection = Builders<T>.Projection.Expression<T1>(u => new T1() { Id = u.Id, Name = u.Name }));
var list = Collection.Find(filter).Project(projection).ToList();