使用 .NET Core 和 MongoDB 快速入门 - 控制台应用程序






4.47/5 (7投票s)
在本文中,您将学习如何在 .NET Core 中使用 NoSQL - MongoDB 创建控制台应用程序。
- 下载 CustomizedProject.zip - 63.4 KB
- 下载 CustomizedProject.rar - 58.9 KB
- 下载 AppTest.zip - 61.8 KB
- 下载 AppTest.rar - 57.7 KB
引言
我将演示如何使用 NoSQL - MongoDB 和 C# 官方驱动程序 2.4 版本创建一个非常简单的 .NET Core 应用程序。我假设您对 .NET 框架连接有一点了解。
先决条件
- 要使用该应用程序,您需要安装带有 Update 3 的 Visual Studio 2015,才能拥有 .NET Core(我展示一个 .NET Core 实用程序是我的动力,但您可以使用任何版本的 Visual Studio)。
- 您将需要安装 NoSQL 数据库服务器 MongoDB。您可以在这里找到它。
- 此步骤不是强制性的,但拥有 GUI 友好的应用程序来管理 MongoDB 服务器会很好。您可以下载并安装的众多工具之一是 Mongobooster [https://mongobooster.com/] -> 下载。否则,您也可以从命令提示符工作。我将使用两者的部分功能。
演示
您可以通过 8 个步骤完成此分步应用程序。我尝试回答流程中的一些调试阶段。 尽管如此,如果您发现任何困难,请在评论区发帖。
- 在 C: 盘中创建一个名为“data”的文件夹,并在“data”文件夹中创建一个“db”文件夹。 这将保存您的数据库。 例如 - C:\data
- 现在,您必须启动 MongoDb 实例。 为此,请转到 C:\Program Files\MongoDB\Server\3.2\bin(我假设您已安装或刚刚下载了 MongoDb 默认实例)。 在命令提示符中打开它的 bin,例如 cd C:\Program Files\MongoDB\Server\3.2\bin。 如果您有 3.4 版,您的路径将例如 cd C:\Program Files\MongoDB\Server\3.4\bin 等等。
现在,使用参数 --dbpath 执行 mongod.exe。 示例 - C:\Program Files\MongoDB\Server\3.2\bin>mongod.exe --dbpath C:\data\db
注意: 您还可以为上述作业创建一个 Windows 服务,以便下次轻松使用。
- 到目前为止,您的 MongoDB 服务器已启动并运行。 在结束之前不要关闭此命令提示符。 打开 Mongobooster 并转到创建和连接。 Mongobooster --> 连接 --> 创建 -->(使用所有默认连接端口 27017)--> 保存并连接。
太棒了! 现在您已连接到 Mongo 服务器。
- 右键单击 localhost(左侧面板上的服务器)并创建一个名为“School”的数据库。 然后,右键单击 School 数据库并创建集合。 此集合不过是 RDBMS 中的表。 只需将其命名为“StudentDetails”。 在这里,可以写一本关于集合、文档、BSON 的书。 要检查一切是否正常,请右键单击 StudentDetails 并选择查看文档。 不用担心,您找不到任何记录,但在窗口中查询。
- 现在,我们准备好后端了,所以来到 Visual Studio -> 文件 -> 新建 -> 项目 -> 控制台应用程序(选择 .NET Core 但可选)-> 创建。
- 右键单击引用以获取 NuGet 包管理器,以获取与 MongoDB 连接的驱动程序。 在“浏览”中,搜索 MongoDB.Driver 驱动程序并安装它。 对于此示例,我使用的是 2.4 版。
- 将以下代码替换为您 Program.cs 文件中的代码。
using System;
//MongoDB.Driver
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Bson.Serialization;
namespace AppTest
{
public class ProfileIdGenerator : IIdGenerator
{
public object GenerateId(object container, object document)
{
return "Test-"+ Guid.NewGuid().ToString();
}
public bool IsEmpty(object id)
{
return id == null || String.IsNullOrEmpty(id.ToString());
}
}
public class Students
{
[BsonId(IdGenerator = typeof(ProfileIdGenerator))]
public string ProfileId { get; set; }
//[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
//public string ProfileId { get; set; }
//[BsonId]
//public ObjectId ProfileId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
public string Age { get; set; }
}
public class Program
{
protected static IMongoClient _client;
protected static IMongoDatabase _database;
public static Students GetStudent()
{
Console.WriteLine("Please enter student first name : ");
string FNm = Console.ReadLine();
Console.WriteLine("Please enter student last name : ");
string LNm = Console.ReadLine();
Console.WriteLine("Please enter student age : ");
string StudentAge = Console.ReadLine();
Console.WriteLine("Please enter city name : ");
string StudentCity = Console.ReadLine();
Students student = new Students()
{
FirstName = FNm,
LastName = LNm,
Age = StudentAge,
City = StudentCity,
};
return student;
}
public void CRUDwithMongoDb()
{
_client = new MongoClient();
_database = _client.GetDatabase("School");
var _collection = _database.GetCollection<Students>("StudentDetails");
Console.WriteLine
("Press select your option from the following\n1 - Insert\n2 - Update One Document\n3 - Delete\n4 - Read All\n");
string userSelection = Console.ReadLine();
switch (userSelection)
{
case "1":
//Insert
_collection.InsertOne(GetStudent());
break;
case "2":
//Update
var obj1 = GetStudent();
_collection.FindOneAndUpdate<Students>
(Builders<Students>.Filter.Eq("FirstName", obj1.FirstName),
Builders<Students>.Update.Set("LastName", obj1.LastName).Set("City", obj1.City).Set("Age", obj1.Age));
break;
case "3":
//Find and Delete
Console.WriteLine("Please Enter the first name to delete the record(so called document) : ");
var deletefirstName = Console.ReadLine();
_collection.DeleteOne(s => s.FirstName == deletefirstName);
break;
case "4":
//Read all existing document
var all = _collection.Find(new BsonDocument());
Console.WriteLine();
foreach (var i in all.ToEnumerable())
{
Console.WriteLine(i.ProfileId + " " + i.FirstName + "\t" + i.LastName + "\t" + i.Age + "\t" + i.City);
}
break;
default:
Console.WriteLine("Please choose a correct option");
break;
}
//To continue with Program
Console.WriteLine("\n--------------------------------------------------------------\nPress Y for continue...\n");
string userChoice = Console.ReadLine();
if (userChoice == "Y" || userChoice == "y")
{
this.CRUDwithMongoDb();
}
}
public static void Main(string[] args)
{
Program p = new Program();
p.CRUDwithMongoDb();
//Hold the screen by logic
Console.WriteLine("Press any key to trminated the program");
Console.ReadKey();
}
}
}
8. 只需运行 (Crl + F5) 控制台应用程序。
结论
在此应用程序中,我已经演示了使用 .NET Core 和 MongoDB 的 CRUD 操作。 演示的项目可在本文中找到,名称为 AppTest.rar。 此外,您可以在我的博客此处了解有关将 BsonDocument 自定义为我们自己的格式的信息。 NoSQL 可以在不同的行(称为文档)中具有不同数量的列(字段)。 ID 也可以自定义,而不是 FirstName,但对于此示例,我采用了一个非常简单的应用程序。 还提供了 CustomizedProject zip,我已经在我的博客中讨论过。
如果您喜欢这项工作,请高度评价它,喜欢/分享这篇文章,并订阅我的个人资料以获取更多更新。 谢谢!