Hi,
DeleteOneAsync() and DeleteManyAsync()
are the two functions in MongoDB driver which is used to delete the records
from the MongoDB from C# language. DeleteOneAsync() is used to delete single record from the
MongoDB and DeleteManyAsync()
is used to delete one or more number of records from the MongoDB.
In the below code, I am deleting record
with ‘MasterID’ as ‘140’
and deleting the record with ‘MasterID’ less
than ‘1000’
C#: .Net 4.5 & MongoDB Driver 2.0
using System;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Driver.Core;
using MongoDB.Bson;
namespace Deldata
{
class Program
{
static void Main(string[] args)
{
callMain(args).Wait();
Console.ReadLine();
}
static async Task callMain(string[] args)
{
var conString = "mongodb://localhost:27017";
var Client = new MongoClient(conString);
var DB = Client.GetDatabase("test");
var collection = DB.GetCollection<BsonDocument>("MasterIds");
//deleting
single record
var Deleteone = await collection.DeleteOneAsync(
Builders<BsonDocument>.Filter.Eq("MasterID", 140));
//deleting
multiple record
var DelMultiple = await collection.DeleteManyAsync(
Builders<BsonDocument>.Filter.Lt("MasterID",
1000));
//retrieve's
data
await collection.Find(new BsonDocument())
.ForEachAsync(x => Console.WriteLine(x));
}
}
}