reza ghasemi
Reza Ghasemi

Follow

Reza Ghasemi

Follow
how to get started with MongoDB in Dotnet Core

how to get started with MongoDB in Dotnet Core

reza ghasemi's photo
reza ghasemi
·Dec 29, 2022·

4 min read

Play this article

Table of contents

  • Creating a .NET Core project
  • Installing the MongoDB Driver
  • Connecting to the MongoDB database
  • CRUD Operations with MongoDB in .NET Core
  • Conclusion

MongoDB is a popular NoSQL database that is widely used for storing large amounts of data. It is known for its flexible schema, high performance, and scalability. In this tutorial, we will learn how to use MongoDB with .NET Core, a cross-platform, open-source framework for building modern applications.

Prerequisites

Before we get started, make sure you have the following software installed on your system:

  • .NET Core 3.1 or later

  • MongoDB 4.4 or later

You can download the latest version of .NET Core from the official website (dotnet.microsoft.com/download) and MongoDB from the MongoDB website (mongodb.com/download-center).

Creating a .NET Core project

First, let's create a new .NET Core project. Open a command prompt or terminal and navigate to the directory where you want to create the project. Then, run the following command:

dotnet new console -o MongoDBDemo

This will create a new console application called "MongoDBDemo".

Installing the MongoDB Driver

Next, we need to install the MongoDB driver for .NET. The MongoDB driver is a NuGet package that allows us to connect to and interact with a MongoDB database from our .NET application.

To install the MongoDB driver, navigate to the project directory and run the following command:

dotnet add package MongoDB.Driver

This will install the latest version of the MongoDB driver.

Connecting to the MongoDB database

Now that we have the MongoDB driver installed, we can start interacting with the database.

To connect to the database, we need to create a MongoClient object and pass it the connection string. The connection string specifies the hostname and port of the MongoDB server, as well as the database name.

Here's an example of how to create a MongoClient object and connect to a database:

string connectionString = "mongodb://localhost:27017";
MongoClient client = new MongoClient(connectionString); 
IMongoDatabase database = client.GetDatabase("mydatabase");

In this example, we are connecting to a MongoDB server running on localhost (the default hostname for a local MongoDB installation) on port 27017 (the default port for MongoDB). We are also specifying the database name as "mydatabase".

CRUD Operations with MongoDB in .NET Core

Now that we have a connection to the database, we can start performing CRUD (create, read, update, delete) operations.

Creating a document

To insert a document into a collection, we first need to get a reference to the collection using the IMongoDatabase.GetCollection method. Then, we can use the InsertOneAsync method to insert a single document.

Here's an example of how to insert a document into a collection:

// Get a reference to the collection
IMongoCollection collection = database.GetCollection("mycollection");
// Create a document
BsonDocument document = new BsonDocument { {"name", "Reza"}, {"age", 30}, {"city", "New York"} };
await collection.InsertOneAsync(document);

Reading a document

To read a document from a collection, we can use the FindAsync method to query the collection and retrieve the documents that match a filter.

Here's an example of how to retrieve a document from a collection:

// Build a filter
var filter = Builders.Filter.Eq("name", "Reza");
// Find the document
var result = await collection.FindAsync(filter);
// Iterate through the results
foreach (var doc in result.ToEnumerable())
    {
        Console.WriteLine(doc);
    }

In this example, we are querying the collection for documents with the name "Reza". The FindAsync method returns a cursor that we can iterate through to retrieve the matching documents.

Updating a document

To update a document in a collection, we can use the ReplaceOneAsync method to replace the entire document.

Here's an example of how to update a document in a collection:

// Build a filter
var filter = Builders<BsonDocument>.Filter.Eq("name", "Reza");
// Create a new document with the updated values
BsonDocument updatedDocument = new BsonDocument
{
    {"name", "Reza"},
    {"age", 31},
    {"city", "New York"}
};
// Replace the document
await collection.ReplaceOneAsync(filter, updatedDocument);

In this example, we are updating the document with the name "Reza" by replacing it with a new document with updated values.

Deleting a document

To delete a document from a collection, we can use the DeleteOneAsync method to delete a single document that matches a filter.

Here's an example of how to delete a document from a collection:

// Build a filter
var filter = Builders<BsonDocument>.Filter.Eq("name", "Reza");

// Delete the document
await collection.DeleteOneAsync(filter);

In this example, we are deleting the document with the name "Reza".

Conclusion

In this tutorial, we learned how to use MongoDB with .NET Core to perform CRUD operations. We saw how to connect to the database, insert documents, query for documents, update documents, and delete documents.

I hope this helps get you started with using MongoDB in .NET Core! Let me know if you have any questions.

Did you find this article valuable?

Support reza ghasemi by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this