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);
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With