16.8. Deleting Documents in a MongoDB Collection

Problem

You want to delete one or more documents in a MongoDB collection.

Solution

Use the findAndRemove method of the Casbah MongoCollection class to delete one document at a time, or use the remove method to delete one or more documents at a time.

The following code uses findAndRemove to delete the document whose symbol field is AAPL:

val query = MongoDBObject("symbol" -> "AAPL")
val result = collection.findAndRemove(query)
println("result: " + result)

When a document is deleted, the findAndRemove method returns the document that was deleted, wrapped in a Some:

result: Some({ "_id" : { "$oid" : "50255d1d03644925d83b3d07"} ,
  "symbol" : "AAPL" , "price" : 600.0})

If nothing is deleted, such as when you try to delete a document that doesn’t exist, the result is None:

result: None

Therefore, you’ll probably want to handle this using a match expression, as shown in the previous recipe.

To delete multiple documents from the collection, specify your search criteria when using the remove method, such as deleting all documents whose price field is greater than 500:

collection.remove("price" $gt 500)

The following method is dangerous: it shows how to delete all documents in the current collection:

// removes all documents
def deleteAllObjectsFromCollection(coll: MongoCollection) {
  coll.remove(MongoDBObject.newBuilder.result)
}

(Be careful with that one.)

Discussion

If you’ve been following along with the MongoDB recipes in this chapter, you can experiment ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.