How to perform delete operation in MongoDB?
In this article, we will learn how to delete the data from MongoDB using Robo 3T. We will learn from the basics because I have written this article focusing on the beginners. In my previous article, we learned the Insert operations in MongoDB. You can check that from here.
Prerequisites
- Visual Studio
- MongoDB installed
- Robo 3T
You can check how to set up the MongoDB environment from here.
Steps to delete the data from MongoDB Table (Collection).
Delete Method in MongoDB
- Remove() - Using this function, we can delete one or all data that matches the search criteria
- deleteone() - Using the deleteone() function, we can delete one document from the Table (Collection), even if multiple items match the criteria
- deletemany() - Using the deletemany() function, we can delete all the matching data
Step 1. Open Visual Studio, create a new console application, and rename it as DeleteOperaion.
Step 2. Add MongoDB Drivers for C# using NuGet Package Manager.
Step 3. Add the Namespace.
- using MongoDB.Driver;
- using MongoDB.Bson;
Step 4. Now, add a connection string.
var connectionString = "mongodb://localhost";
var Client = new MongoClient(connectionString);
We want to delete the data from Employeedetails Table from Employee Database. We will try to find the data using the Name field and delete the data based on the name.
Step 5. Get the database and collection in the database.
var DB = Client.GetDatabase("Employee");
var collection = DB.GetCollection<BsonDocument>("EmployeeDetails");
Step 6. Now, find the Data from Table based on the name field to search. Then, we used a filter and deleted the matching data from table.
var DeleteRecored= collection.DeleteOne(
Builders<BsonDocument>.Filter.Eq("Name", "Sanwar"));
Now, check the complete code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Bson;
namespace DeleteOperation
{
class Program
{
static void Main(string[] args)
{
var connectionString = "mongodb://localhost";
var Client = new MongoClient(connectionString);
var DB = Client.GetDatabase("Employee");
var collection = DB.GetCollection<BsonDocument>("EmployeeDetails");
var DeleteRecored= collection.DeleteOne(
Builders<BsonDocument>.Filter.Eq("Name", "Sanwar"));
Console.WriteLine("Delete Data");
Console.ReadLine();
}
}
}
Before running the program, check the table data.
Now, run the program and check the table. We search the data based on the Name field and delete the matched results from the table.
Summary
In this article, we have learned how we can delete data from a database. We deleted the data from the database using a console application.