MongoDB

Delete or Remove data or documents from collection using C# and MongoDB

You can use the DeleteOneAsync method and the DeleteManyAsync method to remove documents from a collection. The method takes a conditions document that determines the documents to remove.

Follow the Install and Connect to MongoDB step to connect to a running MongoDB instance.

The following operation removes all documents that match the specified condition.

 using System;  
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
namespace MongoDB
{
class Program
{
static void Main(string[] args)
{
DeleteDoc(args).Wait();
Console.WriteLine("Press Enter");
Console.ReadLine();
}
static async Task DeleteDoc(string[] args)
{
var _connectionString = "mongodb://localhost:27017";
var _client = new MongoClient(_connectionString);
var _database = _client.GetDatabase("blog");
var _collection = _database.GetCollection("users");
var _filter = Builders.Filter.Eq("Name", "Test");
var _result = await _collection.DeleteManyAsync(_filter);
}
}
}

Leave a comment