❌Delete

Delete one document

To delete a single document, create a filter definition that matches the document you want to remove and call the DeleteOne method on a IMongoCollection<T> reference.

IMongoCollection<T>
    .DeleteOne(<filter>)

The samples filter a User document by its Id and removes it from the collection.

DeleteDocuments.cs
// get a collection reference
var personsCollection = usersDatabase
    .GetCollection<User>(Constants.UsersCollection);

// find a person using an equality filter on its id
var filter = Builders<User>.Filter.Eq(person => person.Id, appPerson.Id);

// delete the person
var personDeleteResult = await personsCollection.DeleteOneAsync(filter);
if (personDeleteResult.DeletedCount == 1)
{
    Utils.Log($"Document {appPerson.Id} deleted");
}

Delete the first document in the collection

To delete the first document in the collection, simply use an empty filter definition.

Delete multiple documents

To remove more that one documents at the same time, create a filter definition to match the documents you wish to delete and use the DeleteMany method on an IMongoCollection<T>.

Syntax: IMongoCollection<T>.DeleteMany(<filter>)

The following example shows how to delete user documents based on the salary field .

Delete all documents

To delete all documents in a collection, you can use the DeleteMany method with an empty filter. If you want though to clear the entire collection, it's faster to just drop it.

Last updated