Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete multiple MongoDB documents in one query

Tags:

c#

mongodb

I'm trying to play around with MongoDB and have created a demo console application. I want to delete a bunch of documents. At the moment I’m deleting one by one with a loop. My question is: how can I delete all in one query?

I have list of Bson documents to delete in a C# list. Here is my current query.

IMongoClient _Client1 = new MongoClient("mongodb://10.80.3.199:27017");
IMongoDatabase _Database1 = _Client1.GetDatabase("EventManagement-02");
IMongoCollection<BsonDocument> collection = _Database1.GetCollection<BsonDocument>("TestResults");
try
{
    List<BsonDocument> insCollection = new List<BsonDocument>();
    for (int i = 0; i < inserted.Count; i++)
    {
        var filter = Builders<BsonDocument>.Filter.Eq("_id", inserted[i].Id);
        await collection.DeleteManyAsync(filter);
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
like image 364
Pradeep Asanka Avatar asked Dec 05 '25 22:12

Pradeep Asanka


1 Answers

You can simply write the code like this (without the loop):

var filter = Builders<BsonDocument>.Filter.In("_id", inserted.Select(i => i.Id));
await collection.DeleteManyAsync(filter);
like image 135
DiplomacyNotWar Avatar answered Dec 08 '25 12:12

DiplomacyNotWar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!