Travis Laborde
Travis Laborde

Reputation: 1343

How to remove one 'document' by 'ID' using the Official C# Driver for MongoDB?

Can someone please show me, if there is a better way to remove one document from MongoDB using the Official C# Driver than what I have below-

var query = Query.EQ("_id", a.Id);
database.GetCollection<Animal>("Animal").Remove(query);

This code works, but seems too much work to me. The "Save" command for example- takes an instance and updates it. I want something like- Remove(item).

Remarks: I'm trying to use the official driver of C# rather than NoRM or Samus which seems out of date.

Upvotes: 30

Views: 40916

Answers (6)

Kaveh Naseri
Kaveh Naseri

Reputation: 1266

If you only want to delete a docuement from a collection :

public async Task<bool> Delete(string id)
{
    FilterDefinition<YourModel> filter = Builders<YourModel>.Filter.Eq(p => p.Id, id);

    var deleteResult = await _context.YourModelCollection.DeleteOneAsync(filter);

    return deleteResult.IsAcknowledged && deleteResult.DeletedCount > 0;
}

And if you want to delete all the docuements :

public async Task<bool> DeleteAll()
{
    FilterDefinition<YourModel> filter = Builders<YourModel>.Filter.Empty;

    var deleteResult = await _context.YourModelCollection.DeleteManyAsync(filter);

    return deleteResult.IsAcknowledged && deleteResult.DeletedCount > 0;
}

Upvotes: 0

Eugen
Eugen

Reputation: 51

var filter = Builders<BsonDocument>.Filter.Eq("_id",ObjectId.Parse(id));
var x = data.DeleteOne(filter);

I am using this with the current version ( in 2019 ), and it works.

Upvotes: 1

Minhas Kamal
Minhas Kamal

Reputation: 22156

The Simplest Way

Remove a document from a collection for C# MongoDB Driver (v2.0 or later)-

collection.DeleteOne(a => a.Id==id);

Or-

await collection.DeleteOneAsync(a => a.Id==id);

Upvotes: 27

mialkin
mialkin

Reputation: 2781

My ASP.NET Core MVC controller's action accepts Id as a string parameter. Then I parse it and use the result in the DeleteOne() statement:

[HttpPost]
public IActionResult Delete(string id)
{
    ObjectId objectId = ObjectId.Parse(id);
    DbContext.Users.DeleteOne(x => x.Id == objectId);
    return null;
}

Upvotes: 2

Ostati
Ostati

Reputation: 4741

If the [id] is string, you must use ObjectId instance explicitly.

var query = Query.EQ("_id", ObjectId.Parse(id));

Upvotes: 23

Eve Freeman
Eve Freeman

Reputation: 33155

That's the way you do it. I'm sure you know this, but if you want to put it on one line you could combine it so you don't need to define a query variable:

collection.Remove(Query.EQ("_id", a.Id));

Upvotes: 35

Related Questions