Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 647
Travis Laborde Avatar asked Jan 15 '12 02:01

Travis Laborde


People also ask

How do you use deleteOne?

To delete a record, or document as it is called in MongoDB, we use the deleteOne() method. The first parameter of the deleteOne() method is a query object defining which document to delete. Note: If the query finds more than one document, only the first occurrence is deleted.

When multiple documents match the filter supplied to DB collection deleteOne () which document will be deleted from the collection?

deleteone() The deleteOne() method deletes the first document from the collection that matches the given selection criteria. It will delete/remove a single document from the collection. It takes four parameters, the first parameter is the selection criteria and the others are optional.

How do I remove all files from a collection in MongoDB?

To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.


1 Answers

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)); 
like image 195
Eve Freeman Avatar answered Oct 02 '22 22:10

Eve Freeman