注:本文首發于碼友網--《.NET Core(.NET 6)控制臺應用程序與MongoDB Atlas入門實戰示例教程詳解》
.NET Core(.NET 6)控制臺應用程序與MongoDB Atlas入門示例教程詳解概述MongoDB 是一個基于分布式文件存儲的數據庫,由C++ 語言編寫,旨在為 WEB 應用提供可擴展的高性能數據存儲解決方案。
MongoDB 是一個介于關系數據庫和非關系數據庫之間的產品,是非關系數據庫當中功能最豐富,最像關系數據庫的。
與關系型數據庫不同,MongoDB 的數據以類似于 JSON 格式的二進制文檔存儲:
{ name: "Angeladady", age: 18, hobbies: ["Steam", "Guitar"]}
文檔型的數據存儲方式有幾個重要好處:
數據類型可以對應到語言的數據類型,如數組類型(Array)和對象類型(Object);可以嵌套,有時關系型數據庫涉及幾個表的操作,在MongoDB中一次就能完成,可以減少昂貴的連接花銷;不對數據結構加以限制,不同的數據結構可以存儲在同一張表。開始MongoDB Atlas之旅準備工作在開始本文的.NET 6 + MongoDB Atlas實戰之前,請先準備一個MongoDB Atlas賬號以及一個Atlas集群(Sandbox集群)。
MongoDB Atlas 是一個 MongoDB 數據庫即服務平臺,可以為你配置和托管數據庫。
MongoDB Atlas Sandbox集群允許你配置一個內存共享,存儲空間為512MB的3節點的開發測試集群(免費)
申請MongoDB Atlas的免費集群請參數:MongoDB Atlas 入門教程
創建.NETCore(.NET 6)控制臺應用程序本文使用Visual Studio 2022進行示例項目開發
打開Visual Studio 2022,創建一個空白解決方案,取名為MongoDBDemo。之后,右鍵單擊解決方案,選擇添加-->新建項目,在添加新項目窗口中,選擇控制臺應用,如下:
之后,在配置新項目對話框中,填寫項目名稱(MongoDBDemo.ConsoleApp)和位置,如下:
在其他信息對話框中,框架選擇**.NET 6.0(長期支持)**,如下:
點擊創建,Visual Studio將自動創建項目。
安裝基于.NET6的MongoDB驅動NuGet程序包右擊MongoDBDemo.ConsoleApp的依賴項-->管理NuGet程序包,如下:
在打開的NuGet包管理器的搜索框中,輸入關鍵詞MongoDB.Driver,然后選中MongoDB.Driver項目,最后點擊安裝以在項目中安裝MongoDB的.NET驅動程序包,如下:
使用.NETCore(.NET 6)連接到MongoDB Atlas打開Program.cs文件,現在我們使用MongoClient來建立.NET 6應用程序與MongoDB Atlas之間的連接,代碼如下:
using MongoDB.Driver;var connectionString = "MONGODB_ATLAS_URL";var client = new MongoClient(connectionString);var databas = client.ListDatabaNames().ToList();foreach (var databa in databas){ Console.WriteLine(databa);}
其中,上例代碼中的MONGODB_ATLAS_URL可以在MongoDB Atlas集群中獲取到,如下所示:
注:不同用戶的MongoDB Atlas群集地址不同,請替換成你自己的,<password>也改成你自己的MongoDB賬號的對應密碼。
配置好MongoDB的連接字符串后,運行MongoDBDemo.ConsoleApp控制臺應用程序,如果配置正確,將得到類似如下的輸出:
sample_geospatialsample_mflixsample_restaurantssample_suppliessample_trainingsample_weatherdataadminlocal
這里筆者導入了一些MongoDB官方的示例數據庫,所以,你運行的結果可能與本文的有所不同。
以上是.NET 6程序連接到MongoDB Atlas服務器并列出了當前集群中所有的數據庫。
使用.NETCore(.NET 6)向MongoDB Atlas集群數據庫中寫入數據在集群中創建一個名為demo的數據庫,集合(Collection)名稱為dc_ur,如下圖:
打開Visual Studio,在MongoDBDemo.ConsoleApp項目中創建一個命名為Models的文件夾,并在其中創建Ur.cs的用戶類,其屬性設置如下:
namespace MongoDBDemo.ConsoleApp.Models{ public class Ur { public ObjectId Id { get; t; } public string Name { get; t; } public string Password { get; t; } public DateTime CreatedAt { get; t; } public bool IsActive { get; t; } public int Age { get; t; } public long Order { get; t; } public string Description { get; t; } }}
為了建立C#實體類與MongoDB字段之間的映射關系,需要使用MongoDB.Bson中的特性對Ur類的屬性進行標記,如下:
using MongoDB.Bson;using MongoDB.Bson.Serialization.Attributes;namespace MongoDBDemo.ConsoleApp.Models{ public class Ur { [BsonElement("_id")] public ObjectId Id { get; t; } [BsonElement("name")] public string Name { get; t; } [BsonElement("password")] public string Password { get; t; } [BsonElement("created_at")] //[BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime CreatedAt { get; t; } [BsonElement("is_active")] public bool IsActive { get; t; } [BsonElement("age")] public int Age { get; t; } [BsonElement("order")] public long Order { get; t; } [BsonElement("description")] public string Description { get; t; } }}
以上主要使用了BsonElement特性來映射實體類與MongoDB字段之間的映射關系。
接下來,使用.NET 6的Ur類向MongoDB的dc_ur數據庫中寫入數據,示例代碼如下:
using MongoDB.Driver;using MongoDBDemo.ConsoleApp.Models;var dbName = "demo";var connectionString = "MONGODB_ATLAS_URL";var client = new MongoClient(connectionString);var databas = client.ListDatabaNames().ToList();foreach (var databa in databas){ Console.WriteLine(databa);}var dcCollection = client.GetDataba(dbName).GetCollection<Ur>("dc_ur");var random = new Random();var count = 0L;CreateUr();Console.ReadKey();// 創建用戶void CreateUr(){ // 查詢當前數據庫中有多少條記錄 count = dcCollection.CountDocuments("{}"); dcCollection.InrtOne(new Ur { Age = random.Next(10, 60), CreatedAt = DateTime.Now, IsActive = true, Name = $"Rector_{count + 1}", Password = "123456", Order = count + 1 });}
運行以上示例程序,再打開MongoDB Atlas面板,可以看到.NET 6程序寫入的數據,如下:
.NET Core(.NET 6)查詢MongoDB數據這里,我們查詢dc_ur集合中的所有用戶記錄,示例代碼如下:
using MongoDB.Driver;using MongoDBDemo.ConsoleApp.Models;var dbName = "demo";var connectionString = "MONGODB_ATLAS_URL";var client = new MongoClient(connectionString);var dcCollection = client.GetDataba(dbName).GetCollection<Ur>("dc_ur");FindAllUrs();Console.ReadKey();void FindAllUrs(){ var count = dcCollection.CountDocuments("{}"); Console.WriteLine($"總用戶數:{count}"); var urs = dcCollection.AsQueryable().ToList(); foreach (var ur in urs) { Console.WriteLine($"id:{ur.Id},name:{ur.Name},password:{ur.Password},created_at:{ur.CreatedAt},is_active:{ur.IsActive},order:{ur.Order},age:{ur.Age}"); }}
運行結果如下:
總用戶數:1id:6204c4104c7002c60e09ad72,name:Rector_1,password:123456,created_at:2022-02-10 07:51:44,is_active:True,order:1,age:32.NET Core(.NET 6)使用Update更新MongoDB數據
using MongoDB.Driver;using MongoDBDemo.ConsoleApp.Models;var dbName = "demo";var connectionString = "MONGODB_ATLAS_URL";var client = new MongoClient(connectionString);var dcCollection = client.GetDataba(dbName).GetCollection<Ur>("dc_ur");UpdateUr();FindAllUrs();Console.ReadKey();void UpdateUr(){ var update = Builders<Ur>.Update.Set("age", 36); dcCollection.FindOneAndUpdate(x => x.Order == 1, update);}void FindAllUrs(){ var count = dcCollection.CountDocuments("{}"); Console.WriteLine($"總用戶數:{count}"); var urs = dcCollection.AsQueryable().ToList(); foreach (var ur in urs) { Console.WriteLine($"id:{ur.Id},name:{ur.Name},password:{ur.Password},created_at:{ur.CreatedAt},is_active:{ur.IsActive},order:{ur.Order},age:{ur.Age}"); }}
運行結果如下:
總用戶數:1id:6204c4104c7002c60e09ad72,name:Rector_1,password:123456,created_at:2022-02-10 07:51:44,is_active:True,order:1,age:36
可以看到,用戶Order=1的Age已經由原來的32更新成了當前的36,說明更新操作成功。
.NET Core(.NET 6)使用Replace替換MongoDB數據當然,MongoDB還有Replace的API,可以將集合中的數據替換成新的數據,示例如下:
using MongoDB.Driver;using MongoDBDemo.ConsoleApp.Models;var dbName = "demo";var connectionString = "MONGODB_ATLAS_URL";var client = new MongoClient(connectionString);var dcCollection = client.GetDataba(dbName).GetCollection<Ur>("dc_ur");ReplaceUr();FindAllUrs();Console.ReadKey();void ReplaceUr(){ var item = dcCollection.Find(x => x.Order == 1).FirstOrDefault(); if (item != null) { item.Age = 60; item.Name = "Rector Liu"; item.Description = "修改(替換)"; dcCollection.ReplaceOne(x => x.Order == 1, item, new ReplaceOptions()); }}void FindAllUrs(){ var count = dcCollection.CountDocuments("{}"); Console.WriteLine($"總用戶數:{count}"); var urs = dcCollection.AsQueryable().ToList(); foreach (var ur in urs) { Console.WriteLine($"id:{ur.Id},name:{ur.Name},password:{ur.Password},created_at:{ur.CreatedAt},is_active:{ur.IsActive},order:{ur.Order},age:{ur.Age}"); }}
運行結果如下:
總用戶數:1id:6204c4104c7002c60e09ad72,name:Rector Liu,password:123456,created_at:2022-02-10 07:51:44,is_active:True,order:1,age:60.NET Core(.NET 6)刪除MongoDB數據
.NET Core(.NET 6)刪除MongoDB的數據操作如下:
using MongoDB.Driver;using MongoDBDemo.ConsoleApp.Models;var dbName = "demo";var connectionString = "MONGODB_ATLAS_URL";var client = new MongoClient(connectionString);var dcCollection = client.GetDataba(dbName).GetCollection<Ur>("dc_ur");DeleteUr();FindAllUrs();Console.ReadKey();void DeleteUr(){ dcCollection.DeleteOne(x => x.Id == new MongoDB.Bson.ObjectId("6204c4104c7002c60e09ad72"));}void FindAllUrs(){ var count = dcCollection.CountDocuments("{}"); Console.WriteLine($"總用戶數:{count}"); var urs = dcCollection.AsQueryable().ToList(); foreach (var ur in urs) { Console.WriteLine($"id:{ur.Id},name:{ur.Name},password:{ur.Password},created_at:{ur.CreatedAt},is_active:{ur.IsActive},order:{ur.Order},age:{ur.Age}"); }}
運行結果如下:
總用戶數:0
好了,以上即是本文為大家分享的.NET Core(.NET 6)控制臺應用程序與MongoDB Atlas的入門實戰示例教程,希望對你了解、學習在.NET Core(.NET 6)應用程序中如何使用MongoDB數據庫有所幫助。
本文發布于:2023-02-28 20:03:00,感謝您對本站的認可!
本文鏈接:http://www.newhan.cn/zhishi/a/167765200174977.html
版權聲明:本站內容均來自互聯網,僅供演示用,請勿用于商業和其他非法用途。如果侵犯了您的權益請與我們聯系,我們將在24小時內刪除。
本文word下載地址:控制臺應用程序(控制臺應用程序是什么).doc
本文 PDF 下載地址:控制臺應用程序(控制臺應用程序是什么).pdf
| 留言與評論(共有 0 條評論) |