. NET Core(.NET 6) console application and MongoDB Atlas getting started sample tutorial details

Posted by MatrixDancer on Mon, 14 Feb 2022 07:24:41 +0100

Note: This article was first published in Code friend network–<Introduction to. NET Core(.NET 6) console application and MongoDB Atlas>

. NET Core(.NET 6) console application and MongoDB Atlas getting started sample tutorial details

summary

MongoDB is a database based on distributed file storage and written in C + + language. It aims to provide scalable high-performance data storage solutions for WEB applications.

MongoDB is a product between relational database and non relational database. It is the most functional and relational database among non relational databases.

Unlike relational databases, MongoDB's data is stored in binary documents similar to JSON 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 and Object;
  • It can be nested. Sometimes the relational database involves the operation of several tables, which can be completed in MongoDB at one time, which can reduce the expensive connection cost;
  • There are no restrictions on data structures. Different data structures can be stored in the same table.

Start MongoDB Atlas Tour

preparation

At the beginning of this article NET 6 + MongoDB Atlas before actual combat, please prepare a MongoDB Atlas account and an Atlas cluster (Sandbox cluster).

MongoDB Atlas is a MongoDB database as a service platform, which can configure and host the database for you.

MongoDB Atlas Sandbox cluster allows you to configure a 3-node development and test cluster with memory sharing and 512MB storage space (free)

To apply for a free cluster of MongoDB Atlas, please specify the following parameters: MongoDB Atlas tutorial

establish. NET Core(.NET 6) console application

This article uses Visual Studio 2022 for example project development

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

Then, in the configure new Project dialog box, fill in the project name (MongoDBDemo.ConsoleApp) and location as follows:

In the other information dialog box, select * * Net 6.0 (long term support) * *, as follows:

Click create and Visual Studio will automatically create the project.

Installation is based on NET 6 MongoDB driver NuGet package

Right click mongodbdemo Dependencies of ConsoleApp – > manage NuGet packages as follows:

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

use. NET Core(.NET 6) connects to MongoDB Atlas

Open program CS file. Now we use MongoClient to create it 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 in the above example code_ ATLAS_ The URL can be obtained in the MongoDB Atlas cluster, as shown below:

Note: different users have different MongoDB Atlas cluster addresses. Please replace them with your own, < password > also change the corresponding password of your own MongoDB account.

After configuring the connection string of MongoDB, run mongodbdemo If the console app is configured correctly, it will get the following output:

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 the results you run may be different from those in this article.

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

use. NET Core(.NET 6) writes data to MongoDB Atlas cluster database

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

Open Visual Studio in mongodbdemo Create a folder named Models in the ConsoleApp project and create a user The attributes of the user class of CS are set as follows:

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, MongoDB The attribute in bson marks the attribute of 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 NET 6 User class to MongoDB DC_ Write data to the User database. The example 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();


// Create user
void CreateUser()
{
    // Query the number of records in the current database
    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 to see NET 6 program writes the following data:

. NET Core(.NET 6) query MongoDB data

Here, we query DC_ All user records in the user collection. The example 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($"Total users:{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 operation results are as follows:

Total users: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) Update MongoDB data with Update

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($"Total users:{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 operation results are as follows:

Total users: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) Replace MongoDB data with Replace

Of course, MongoDB also has an API for Replace, which can Replace the data in the collection with new data. An 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 = "modify(replace)";
        dcCollection.ReplaceOne(x => x.Order == 1, item, new ReplaceOptions());
    }
}

void FindAllUsers()
{
    var count = dcCollection.CountDocuments("{}");
    Console.WriteLine($"Total users:{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 operation results are as follows:

Total users: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) delete MongoDB data 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($"Total users:{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 operation results are as follows:

Total users:0

Well, the above is what this article shares for you NET Core(.NET 6) console application and MongoDB Atlas introductory practical example tutorial, I hope you can understand and learn in NET Core(.NET 6) application is helpful in how to use MongoDB database.

The operation results are as follows:

Total users:0

Well, the above is what this article shares for you NET Core(.NET 6) console application and MongoDB Atlas introductory practical example tutorial, I hope you can understand and learn in NET Core(.NET 6) application is helpful in how to use MongoDB database.

Topics: C# Database MongoDB .NET