Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo C# driver find multiple and delete

Tags:

c#

mongodb

I'm using collection.FindOneAndDeleteAsync, but this uses a ton of cpu when used to get many documents. What's the best way to go about finding multiple documents(anywhere from 100 to 50k) and delete, using the c# mongo driver?

Thanks

like image 207
ole Avatar asked May 01 '26 16:05

ole


1 Answers

You need to Find the docs you want to delete, and then delete them using DeleteMany with a filter of _id: {$in: ids}, where ids is an enumerable of the _id values of those documents.

C# example:

public class Entity
{
    public ObjectId id { get; set; }
    public string name { get; set; }
}

// Find the documents to delete
var test = db.GetCollection<Entity>("test");
var filter = new BsonDocument();
var docs = test.Find(filter).ToList();

// Get the _id values of the found documents
var ids = docs.Select(d => d.id);

// Create an $in filter for those ids
var idsFilter = Builders<Entity>.Filter.In(d => d.id, ids);

// Delete the documents using the $in filter
var result = test.DeleteMany(idsFilter);
like image 63
JohnnyHK Avatar answered May 03 '26 06:05

JohnnyHK