MongoDB in .NET part 7: deleting documents
August 18, 2014 Leave a comment
Introduction
In the previous post in this series we looked at how to update documents. So we now know how to insert, save and modify documents. We also need to be able to remove documents.
Remove and RemoveAll
Removing a document can be performed using the Remove method of IMongoCollection which has similar overloads to Update and returns a WriteConcernResult. However, while Update updates a single document by default even if there are multiple matching ones, Remove removes all matching documents. Most often we’ll remove a single document which matches an ID query but we can certainly construct an IMongoQuery which matches multiple documents. However, even if multiple documents are removed, the group of remove operations are not treated as a transaction. Each removal is a distinct operation.
You can supply a WriteConcern parameter which has the same purpose as in the case of Save and Update. You can also provide a RemoveFlags parameter which has 2 values: None and Single. With Single you can indicate that you only want to remove a single document if the query matches 2 or more documents. “None” simply means no flags which is the default value.
RemoveAll removes all documents in a collection while leaving indexes and metadata intact. There’s also a Drop method which is faster then RemoveAll but removes indexes and metadata too. If you need to remove the entire collection quickly then use the Drop method.
There’s also an atomic version called FindAndRemove which works in much the same way as FindAndUpdate we saw in the previous part.
Demo
We’ll extend the demo application we’ve been working on so far so have it ready in Visual Studio. This will be really simple actually. The Index.cshtml file of Cars already prepared a link for the Delete operation:
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
We don’t yet have a Delete action so let’s add it to the CarsController:
public ActionResult Delete(string id)
{
CarRentalContext.Cars.Remove(Query.EQ("_id", ObjectId.Parse(id)));
return RedirectToAction("Index");
}
As you type Cars.Remove you’ll see the overloads of Remove where you can specify the parameters mentioned above. Run the application, navigate to /cars and press the Delete link on one of the items. The item should be removed from the list of items.
In the next part we’ll look more into MongoDb queries.
View the posts related to data storage here.