Note: This article was first published on -- " .NET Core (.NET 6) Console Application and MongoDB Atlas Getting Started Practical Example Tutorial Detailed Explanation "

.NET Core (.NET 6) console application and MongoDB Atlas introductory sample tutorial

Overview

MongoDB is a database based on distributed file storage, written in C++ language, designed to provide a scalable high-performance data storage solution for WEB applications.

MongoDB is a product between relational databases and non-relational databases. It is the most feature-rich and most like relational databases among non-relational databases.

Unlike relational databases, MongoDB's data is stored as binary documents in a JSON-like format:

{
    name: "Angeladady",
    age: 18,
    hobbies: ["Steam", "Guitar"]
}

Document-based data storage has several important benefits:

  • The data type can correspond to the data type of the language, such as array type (Array) and object type (Object);
  • Can be nested, sometimes relational databases involve operations on several tables, which can be done at one time in MongoDB, which can reduce expensive connection costs;
  • The data structure is not limited, and different data structures can be stored in the same table.

Start your MongoDB Atlas journey

Ready to work

Before starting the .NET 6 + MongoDB Atlas combat in this article, please prepare a MongoDB Atlas account and an Atlas cluster (Sandbox cluster).

MongoDB Atlas is a MongoDB database-as-a-service platform that configures and hosts databases for you.

MongoDB Atlas Sandbox cluster allows you to configure a 3-node dev/test cluster with 512MB of shared memory (free)

To apply for a free cluster of MongoDB Atlas, please parameter: MongoDB Atlas Getting Started Tutorial

Create a .NET Core (.NET 6) console application

This article uses Visual Studio 2022 for sample project development

Open Visual Studio 2022 and create a blank solution named MongoDBDemo . After that, right-click on the solution, select add --> new project , in add new project window, select the console application, as follows:

After that, in the configuration new project dialog box, fill in the project name (MongoDBDemo.ConsoleApp) and location, as follows:

In the Additional Information dialog box, the framework selects .NET 6.0 (long term support) , as follows:

Click to create and Visual Studio will automatically create the project.

Install the .NET 6 based MongoDB driver NuGet package

Right click MongoDBDemo.ConsoleApp Dependency --> Manage NuGet Package , as follows:

In the search box of the opened NuGet package manager, enter the keyword MongoDB.Driver , then select MongoDB.Driver project, and finally click to install the driver package to install the MongoDB driver package in the project as follows:

Connect to MongoDB Atlas using .NET Core (.NET 6)

Open the Program.cs file, now we use MongoClient to establish the connection between the .NET 6 application and MongoDB Atlas, the code is as follows:

using MongoDB.Driver;

var connectionString = "MONGODB_ATLAS_URL";
var client = new MongoClient(connectionString);
var databases = client.ListDatabaseNames().ToList();
foreach (var database in databases)
{
    Console.WriteLine(database);
}

Among them, MONGODB_ATLAS_URL in the above example code can be obtained in the MongoDB Atlas cluster, as shown below:

Note: The MongoDB Atlas cluster address of different users is different, please replace it with your own, and change <password> to the corresponding password of your own MongoDB account.

After configuring the MongoDB connection string, run MongoDBDemo.ConsoleApp console application, if the configuration is correct, you will get output similar to the following:

sample_geospatial
sample_mflix
sample_restaurants
sample_supplies
sample_training
sample_weatherdata
admin
local
Here the author has imported some official MongoDB sample databases, so your results may be different from those in this article.

The above is a .NET 6 program that connects to the MongoDB Atlas server and lists all the databases currently in the cluster.

Write data to the MongoDB Atlas cluster database using .NET Core (.NET 6)

Create a database named demo in the cluster, and the collection name is dc_user , as shown below:

Open Visual Studio, create a folder named Models in the MongoDBDemo.ConsoleApp project, and create User.cs in it with the following properties:

namespace MongoDBDemo.ConsoleApp.Models
{
    public class User
    {
        public ObjectId Id { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
        public DateTime CreatedAt { get; set; }
        public bool IsActive { get; set; }
        public int Age { get; set; }
        public long Order { get; set; }
        public string Description { get; set; }
    }
}

In order to establish the mapping relationship between the C# entity class and the MongoDB field, it is necessary to use the features in MongoDB.Bson to mark the attributes of the User class, as follows:

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace MongoDBDemo.ConsoleApp.Models
{
    public class User
    {
        [BsonElement("_id")]
        public ObjectId Id { get; set; }
        [BsonElement("name")]
        public string Name { get; set; }
        [BsonElement("password")]
        public string Password { get; set; }
        [BsonElement("created_at")]
        //[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime CreatedAt { get; set; }
        [BsonElement("is_active")]
        public bool IsActive { get; set; }
        [BsonElement("age")]
        public int Age { get; set; }
        [BsonElement("order")]
        public long Order { get; set; }
        [BsonElement("description")]
        public string Description { get; set; }
    }
}

The above mainly uses the BsonElement feature to map the mapping relationship between entity classes and MongoDB fields.

Next, use the User class of .NET 6 to write data to the dc_user database of MongoDB. The sample code is as follows:

using MongoDB.Driver;
using MongoDBDemo.ConsoleApp.Models;
var dbName = "demo";
var connectionString = "MONGODB_ATLAS_URL";
var client = new MongoClient(connectionString);

var databases = client.ListDatabaseNames().ToList();
foreach (var database in databases)
{
    Console.WriteLine(database);
}

var dcCollection = client.GetDatabase(dbName).GetCollection<User>("dc_user");
var random = new Random();
var count = 0L;
CreateUser();

Console.ReadKey();


// 创建用户
void CreateUser()
{
    // 查询当前数据库中有多少条记录
    count = dcCollection.CountDocuments("{}");

    dcCollection.InsertOne(new User
    {
        Age = random.Next(10, 60),
        CreatedAt = DateTime.Now,
        IsActive = true,
        Name = $"Rector_{count + 1}",
        Password = "123456",
        Order = count + 1
    });
}

Run the above sample program, and then open the MongoDB Atlas panel, you can see the data written by the .NET 6 program, as follows:

.NET Core (.NET 6) query MongoDB data

Here, we query all user records in the dc_user collection, the sample code is as follows:

using MongoDB.Driver;
using MongoDBDemo.ConsoleApp.Models;
var dbName = "demo";
var connectionString = "MONGODB_ATLAS_URL";
var client = new MongoClient(connectionString);
var dcCollection = client.GetDatabase(dbName).GetCollection<User>("dc_user");
FindAllUsers();
Console.ReadKey();

void FindAllUsers()
{
    var count = dcCollection.CountDocuments("{}");
    Console.WriteLine($"总用户数:{count}");
    var users = dcCollection.AsQueryable().ToList();
    foreach (var user in users)
    {
        Console.WriteLine($"id:{user.Id},name:{user.Name},password:{user.Password},created_at:{user.CreatedAt},is_active:{user.IsActive},order:{user.Order},age:{user.Age}");
    }
}

The results are as follows:

总用户数:1
id: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) uses Update to update MongoDB data

using MongoDB.Driver;
using MongoDBDemo.ConsoleApp.Models;
var dbName = "demo";
var connectionString = "MONGODB_ATLAS_URL";
var client = new MongoClient(connectionString);
var dcCollection = client.GetDatabase(dbName).GetCollection<User>("dc_user");
UpdateUser();
FindAllUsers();
Console.ReadKey();

void UpdateUser()
{
    var update = Builders<User>.Update.Set("age", 36);
    dcCollection.FindOneAndUpdate(x => x.Order == 1, update);
}

void FindAllUsers()
{
    var count = dcCollection.CountDocuments("{}");
    Console.WriteLine($"总用户数:{count}");
    var users = dcCollection.AsQueryable().ToList();
    foreach (var user in users)
    {
        Console.WriteLine($"id:{user.Id},name:{user.Name},password:{user.Password},created_at:{user.CreatedAt},is_active:{user.IsActive},order:{user.Order},age:{user.Age}");
    }
}

The results are as follows:

总用户数:1
id:6204c4104c7002c60e09ad72,name:Rector_1,password:123456,created_at:2022-02-10 07:51:44,is_active:True,order:1,age:36

It can be seen that the Age of user Order=1 has been updated from the original 32 to the current 36 , indicating that the update operation is successful.

.NET Core (.NET 6) uses Replace to replace MongoDB data

Of course, MongoDB also has an API of Replace , which can replace the data in the collection with new data. The example is as follows:

using MongoDB.Driver;
using MongoDBDemo.ConsoleApp.Models;
var dbName = "demo";
var connectionString = "MONGODB_ATLAS_URL";
var client = new MongoClient(connectionString);
var dcCollection = client.GetDatabase(dbName).GetCollection<User>("dc_user");
ReplaceUser();
FindAllUsers();
Console.ReadKey();

void ReplaceUser()
{
    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 FindAllUsers()
{
    var count = dcCollection.CountDocuments("{}");
    Console.WriteLine($"总用户数:{count}");
    var users = dcCollection.AsQueryable().ToList();
    foreach (var user in users)
    {
        Console.WriteLine($"id:{user.Id},name:{user.Name},password:{user.Password},created_at:{user.CreatedAt},is_active:{user.IsActive},order:{user.Order},age:{user.Age}");
    }
}

The results are as follows:

总用户数:1
id: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) delete MongoDB data

.NET Core (.NET 6) deletes MongoDB's data operations as follows:

using MongoDB.Driver;
using MongoDBDemo.ConsoleApp.Models;
var dbName = "demo";
var connectionString = "MONGODB_ATLAS_URL";
var client = new MongoClient(connectionString);
var dcCollection = client.GetDatabase(dbName).GetCollection<User>("dc_user");
DeleteUser();
FindAllUsers();
Console.ReadKey();

void DeleteUser()
{
    dcCollection.DeleteOne(x => x.Id == new MongoDB.Bson.ObjectId("6204c4104c7002c60e09ad72"));
}

void FindAllUsers()
{
    var count = dcCollection.CountDocuments("{}");
    Console.WriteLine($"总用户数:{count}");
    var users = dcCollection.AsQueryable().ToList();
    foreach (var user in users)
    {
        Console.WriteLine($"id:{user.Id},name:{user.Name},password:{user.Password},created_at:{user.CreatedAt},is_active:{user.IsActive},order:{user.Order},age:{user.Age}");
    }
}

The results are as follows:

总用户数:0

Well, the above is the introductory practical example tutorial of .NET Core (.NET 6) console application and MongoDB Atlas shared by this article. I hope you can understand and learn in .NET Core (.NET 6) applications. How to use a MongoDB database helps.


RECTOR
666 声望173 粉丝

计算机科学与技术专业,全栈工程师,码友网创建者、维护者,千星开源项目(DncZeus)项目开发者,专注.NET/.NET Core及相关开发。