Get Started with CRUD Operations in MongoDB using C#: 3 Easy Steps

on Database, Database Management Systems, Uncategorized • February 14th, 2022 • Write for Hevo

CRUD Operations in MongoDB using C#- Featured Image

MongoDB is one of the most commonly used document databases that offer incredible scalability and flexibility, allowing you to query and index data as you see fit. The document model that MongoDB uses simplifies operations for developers without compromising on functionality.

It’s worth mentioning that MongoDB provides official driver support for all major programming languages, including C#, and you can use it to perform CRUD operations. On top of that, it allows you to run ad hoc queries and indexing while aggregating your data in real-time, to access and analyze it conveniently. Before we start talking about CRUD operations in MongoDB using C#, it’s important to understand what MongoDB is and how to set up your system to run CRUD operations in MongoDB using C#. Read on to find out more. 

Table of Contents

What is MongoDB?

MongoDB Logo: CRUD Operations in MongoDB using C#
Image Source- MongoDB

If you work with big data, you would have encountered the problem of fitting diverse data into a rigid relational model. SQL databases or Relational Databases (RDBMS) store information in rows and columns, which are not quite fit for storing high and diverse volumes of data. NoSQL databases like MongoDB are of help there. 

MongoDB is a popular and open-source NoSQL database, offering flexibility to store big data in the form of collections and documents. MongoDB service can be installed as an on-premise instance or a cloud instance based on your preferred subscription. With MongoDB, you get to create rows (or documents) on the fly, without requiring a schema definition beforehand. 

There are drivers available for more than 10 programming languages on MongoDB- C, C++, C#, and .Net, Go, Java, Node.js, Perl, PHP, Python, Motor, Ruby, Scala, Swift, Mongoid. If you’re looking for a viable database where you can store data in flexible, JSON-like documents, you can’t go wrong with MongoDB.

To learn more about MongoDB, and its contrast to SQL Databases, click this guide- MongoDB vs SQL Databases: 4 Comprehensive Aspects. Also check out MongoDB Real-Time Analytics: A Comprehensive Guide.

Simplify Data Migration with Hevo’s No-code Data Pipeline

Hevo Data, a No-code Data Pipeline helps to load data from any data source such as MongoDB, other Databases, SaaS applications, Cloud Storage, SDKs, and Streaming Services and simplifies the ETL process. It supports 100+ data sources (including 40+ free data sources) like MongoDB and is a 3-step process by just selecting the data source, providing valid credentials, and choosing the destination.

GET STARTED WITH HEVO FOR FREE[/hevoButton]

Its completely automated pipeline offers data to be delivered in real-time without any loss from source to destination. Hevo not only loads the data into the desired Data Warehouse/destination but also enriches the data and transforms it into an analysis-ready form without having to write a single line of code.

Check out why Hevo is the Best:

  • Secure: Hevo has a fault-tolerant architecture that ensures that the data is handled in a secure, consistent manner with zero data loss.
  • Schema Management: Hevo takes away the tedious task of schema management & automatically detects the schema of incoming data and maps it to the destination schema.
  • Minimal Learning: Hevo, with its simple and interactive UI, is extremely simple for new customers to work on and perform operations.
  • Hevo Is Built To Scale: As the number of sources and the volume of your data grows, Hevo scales horizontally, handling millions of records per minute with very little latency.
  • Incremental Data Load: Hevo allows the transfer of data that has been modified in real-time. This ensures efficient utilization of bandwidth on both ends.
  • Live Support: The Hevo team is available round the clock to extend exceptional support to its customers through chat, email, and support calls.
  • Live Monitoring: Hevo allows you to monitor the data flow and check where your data is at a particular point in time.
SIGN UP HERE FOR A 14-DAY FREE TRIAL

Running CRUD Operations in MongoDB Using C#

People who are familiar with working on databases, they might already be familiar with CRUD operations. CRUD mainly stands for Create, Read, Update, and Delete. It’s a simple acronym that’s used to describe the four most common features of conventional storage databases. These operations are commonly applied using SQL. 

Almost every other database application features some form of CRUD functionality, and it’s obvious that every programmer has to deal with CRUD operations at some point in their professional career. Since MongoDB does have CRUD functionality (since it’s a NoSQL database) you can still run CRUD Operations in MongoDB Using C#, using its official driver support. 

Prerequisites for Setting Up CRUD Operations in MongoDB Using C#

Running CRUD Operations in MongoDB Using C# provides you with a robust combo-duo that can help you manage your data more effectively. To get started, you are required to have user permissions to access a MongoDB Sample Dataset. You will also require access to your own datasets. 

Apart from that, you’ll need NuGet Packages, Visual Studio Community 2019, Windows 10 or 11, and the C# Driver for MongoDB, as well as their BSON Library.

Set Up CRUD Operations in MongoDB Using C#

To get started with CRUD Operations in MongoDB Using C#, you first need to connect to Visual Studio 2019 on your Windows system. After that, connect your system to a MongoDB Atlas Cluster. Once you do that, the next step is to install the MongoDB Driver for C#. Just open Visual Studio, and follow the steps below:

Step 1: From the menubar, go to Tools

Step 2: Click on NuGet Package Manager. Search for MongoDB.Driver, and install it. 

To get the driver working, you need to add a directive. Here’s the code you should use:

using MongoDB.Driver;

Once you run the directive, the next step is to establish a connection with MongoDB Atlas with the help of a connection string. Once you have the connection in place, you can start running any CRUD operations that you want within the database. The first step, then, is to create data. 

Generating Data in MongoDB Using C#

When running CRUD operations in MongoDB using C#, it’s important to note that data is stored in MongoDB as Binary JSON documents. To establish a connection with a specific collection, you need to begin with a package from NuGet. This is known as MongoDB.Bson. 

To create a BSON document, here’s the code you need to run:

Var document = new BsonDocument
	{
		{ “employee_id”, 100 },
		{ “scores”, new BsonArray
			      {
				New BsonDocument{ {“type”, “review”} {“score”, 8.8 } }
			                 }
			},
			{ “employee_id”, 100}
		};

Creating a CRUD Operation in MongoDB Using C#

Here are the four basic CRUD operations- Create, Read, Update, Delete and the methods to use them:

Create

Once you have a collection, you can then create a new document. To do so, asynchronously, you can simply use the following command:

Await collection.InsertOneAsync(document);

You can also modify this code and use other alternatives like- InsertOne(), InsertOneAsync(), InsertMany(), or InsertManyAsync() methods.

Read 

To read documents in MongoDB using C#, consider using the Find() method. For this to work, use the following code:

var secondDocument = collection.Find(new BsonDocument()).FirstOrDefault();

Console.WriteLine(secondDocument.ToString());

You can also query and read documents by creating a specific filter. For this to work with our original document employee_id, here’s the command you should use:

var filter = Builders<BsonDocument>.Filter.Eq(“employee_id”, 100);

This will create a filter to look for an employee id that equals 100. The C# Driver that’s available for MongoDB offers a variety of ways for users to read data from their database. It makes it easy to query data using both synchronous and asynchronous methods. By using a filter via the Find() method, you can easily query specific records. 

Update

We have explored how to perform two of the four different CRUD operations in MongoDB using C#. To update data, you’ll have to use the same command. 

But first, you need to create a filter to determine which of the documents you need to update. In this example, we’ll focus on the same employee_id document. Here’s the code you can use for that:

var filter = Builders<BsonDocument>.Filter.Eq(“employee_id”, 100);

You can update specific things, like the employee_id.To do that, simply run the following command:

var filter = Builders<BsonDocument>.Update.Set(“department_id”, 28);

Essentially, this will change the department ID for the employee to 28. Once you do this, you can use the UpdateOne() function to make the changes. Additionally, for those cases in which multiple documents need to be updated at once, there are UpdateMany() or UpdateManyAsync() options. 

Delete

Our final function when running CRUD operations in MongoDB using C# is deleted. This refers to the deletion process. To delete a specific record, you need to first define it. Here’s the code that you can use to delete the document we originally created. 

var deleteFilter = Builders<BsonDocument>.Filter.Eq{“employee_id”, 100);

If you use the DeleteOne() command, it’s simply going to delete the first document in the entire collection, as long as it matches the filter. However, when a filter matches more than a single document and all of them need to be deleted, the DeleteMany() or DeleteManyAsync() method can be used.

Conclusion

MongoDB is a very popular database. This guide showed you how to run CRUD operations in MongoDB using C#, making it easier to manage your data. In this guide, we got a better understanding of how to use different filters to match particular documents and then run operations on them. If you want, you can also connect additional analytical applications to run more comprehensive operations on your data and analyze it in greater detail! 

If you use the MongoDB database on a recurring basis and wish to transfer your database files to a secure single location, a Cloud-based Data Warehouse might be the best alternative. Worried about where to start with? A simple and speedy data transfer solution like Hevo ETL helps you in that. 

Hevo Data with its strong integration with 100+ Sources & BI tools such as MongoDB, allows you to not only export data from sources & load data to the destinations, but also transform & enrich your data, & make it analysis-ready so that you can focus only on your key business needs and perform insightful analysis using BI tools. 

Visit our Website to Explore Hevo

Hevo lets you migrate your data from your MongoDB database to any Data Warehouse of your choice like Amazon Redshift, Snowflake, Google BigQuery, or Firebolt within minutes with just a few clicks.

Why not give Hevo a try? Sign Up here for a 14-day free trial and experience the feature-rich Hevo suite firsthand. You can also check our unbeatable pricing and make a decision on your best-suited plan. 

Share your ideas about learning CRUD Operations in MongoDB using C# in the comments area below. Tell us of any other programming languages you’d want us to cover. We’d love to hear your thoughts and ideas.

No Code Data Pipeline For Your Data Warehouse