十年河東,十年河西,莫欺少年窮
學無止境,精益求精
工欲善其事必先利其器,要想使用mongodb,就必須先安裝MongoDb服務,關於MongoDb的安裝網上有很多教程,我使用的是MongoDb 4.2.1 ,據說4.2版本是最穩定的版本。
關於安裝,請參考:https://zhuanlan.zhihu.com/p/136763521 或者自行百度。百度是的時候,記得加上版本4.2哦。
安裝配置過程中,.在瀏覽器中輸入網址:http://localhost:27017/ 。如果服務啟動成功會看到以下一段話:
It looks like you are trying to access MongoDB over HTTP on the native driver port.
這樣就說明你的MongoDB安裝配置成功了。關於mongoDb的可視化工具,大家可選擇:Robomongo,可自行百度下載 :CSDN下載:https://download.csdn.net/detail/u012238360/12328517。
有了MongoDB服務端以后,我們就可以通過CMD命令來創建數據庫,數據表,插入數據,查詢數據了。
關於MongoDb的簡單使用,
根據微軟教程,我整理的相關命令如下:
mongod --dbpath D:\MongoData\data\db --新開啟 mongo --轉換到表 use LogstoreDb --創建表 db.createCollection('LogsForDg') --插入 db.LogsForDg.insertMany([{'methodNo':'cloud-180','data':'{}','CreateTime':'2020-02-02'}]) --查詢 db.LogsForDg.find({}).pretty() --VS2019工具 --安裝包 Install-Package MongoDB.Driver -Version 2.11.0 --創建實體

public class LogsForDgModel { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } [BsonElement("methodNo")] public string methodNo { get; set; } public string data { get; set; } public string CreateTime { get; set; } } public class LogstoreDatabaseSettings : ILogstoreDatabaseSettings { public string LogsCollectionName { get; set; } public string ConnectionString { get; set; } public string DatabaseName { get; set; } } public interface ILogstoreDatabaseSettings { public string LogsCollectionName { get; set; } public string ConnectionString { get; set; } public string DatabaseName { get; set; } }
配置文件如下:

{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "ConnectionStrings": { "WuAnDBContext": ";User ID=sa;" }, "LogstoreDatabaseSettings": { "LogsCollectionName": "LogsForDg", "ConnectionString": "mongodb://localhost:27017", "DatabaseName": "LogstoreDb" } }
MongoDb的操作類如下:

using IotDtos.MongodbDtos; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace IotApi.Helper.mongo { public class LogService { private readonly IMongoCollection<LogsForDgModel> _books; public LogService(ILogstoreDatabaseSettings settings) { var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); _books = database.GetCollection<LogsForDgModel>(settings.LogsCollectionName); } public List<LogsForDgModel> Get() => _books.Find(book => true).ToList(); public LogsForDgModel Get(string id) => _books.Find<LogsForDgModel>(book => book.Id == id).FirstOrDefault(); public LogsForDgModel Create(LogsForDgModel book) { _books.InsertOne(book); return book; } public void Update(string id, LogsForDgModel bookIn) => _books.ReplaceOne(book => book.Id == id, bookIn); public void Remove(LogsForDgModel bookIn) => _books.DeleteOne(book => book.Id == bookIn.Id); public void Remove(string id) => _books.DeleteOne(book => book.Id == id); } }
啟動類如下:
啟動類完整代碼:

public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //MongoDb 選項模式 services.Configure<LogstoreDatabaseSettings>( Configuration.GetSection(nameof(LogstoreDatabaseSettings))); services.AddSingleton<ILogstoreDatabaseSettings>(sp => sp.GetRequiredService<IOptions<LogstoreDatabaseSettings>>().Value); #region 注冊JWT services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(TokenManagement.Secret)), ValidIssuer = TokenManagement.Issuer, ValidAudience = TokenManagement.Audience, ValidateIssuer = false, ValidateAudience = false }; }); #endregion #region 注冊Swagger服務 // 注冊Swagger服務 services.AddSwaggerGen(c => { // 添加文檔信息 c.SwaggerDoc("v1", new OpenApiInfo { Title = "IOT相關接口", Version = "V1" }); //c.SwaggerDoc("demo", new OpenApiInfo { Title = "示例接口", Version = "demo" }); c.DocInclusionPredicate((docName, apiDesc) => apiDesc.GroupName == docName.ToUpper()); var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//獲取應用程序所在目錄(絕對,不受工作目錄影響,建議采用此方法獲取路徑) var xmlPath = Path.Combine(basePath, "IotApi.xml"); c.IncludeXmlComments(xmlPath); #region Jwt //開啟權限小鎖 c.OperationFilter<AddResponseHeadersFilter>(); c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>(); //在header中添加token,傳遞到后台 c.OperationFilter<SecurityRequirementsOperationFilter>(); c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Description = "JWT授權(數據將在請求頭中進行傳遞)直接在下面框中輸入Bearer {token}(注意兩者之間是一個空格) \"", Name = "Authorization",//jwt默認的參數名稱 In = ParameterLocation.Header,//jwt默認存放Authorization信息的位置(請求頭中) Type = SecuritySchemeType.ApiKey }); #endregion }); #endregion #region 注冊SQLSERVER services.AddDbContext<WuAnDBTestContext>(options => options.UseSqlServer(Configuration.GetConnectionString("WuAnDBContext"))); #endregion #region 注冊自定義服務 services.AddScoped<IIotMns, IotMnsService>(); //MongoDb 日志服務類 services.AddSingleton<LogService>(); //MongoDb 日志服務類 #endregion }
結合微軟教程 及我的代碼,即可迅速完成MongoDB的學習。
@博客園好牛逼