Find and delete the specified document in MongoDB
using C# can achieve by using FindOneAndDeleteAsync()
function in MongoDB 2.0 driver with .net 4.5, it deletes the inputted document.
In
the below example MasterIds is
the collection name and MasterID is the column name and deleting
the MasterID with value 11630
C#: .Net 4.5 MongoDB 2.0 driver
using System;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver.Core;
using MongoDB.Driver;
namespace FindAnd2
{
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");
//find
the MasterID with 11630 and delete it
var result = await collection.FindOneAndDeleteAsync(
Builders<BsonDocument>.Filter.Eq("MasterID",
11630),
new FindOneAndDeleteOptions<BsonDocument>
{
Sort = Builders<BsonDocument>.Sort.Descending("MasterID")
}
);
//result
conatins the deleted reocord details
Console.WriteLine(result);
}
}
}