16.6. Updating Documents in a MongoDB Collection
Problem
You want to update one or more documents in a MongoDB collection.
Solution
Use either the findAndModify
or
update
methods from the Casbah
MongoCollection
class, as shown in
this example:
import
com.mongodb.casbah.Imports._
import
Common._
object
Update
extends
App
{
val
collection
=
MongoFactory
.
collection
// findAndModify
// -------------
// create a new Stock object
val
=
Stock
(
"GOOG"
,
500
)
// search for an existing document with this symbol
var
query
=
MongoDBObject
(
"symbol"
->
"GOOG"
)
// replace the old document with one based on the 'google' object
val
res1
=
collection
.
findAndModify
(
query
,
buildMongoDbObject
(
))
println
(
"findAndModify: "
+
res1
)
// update
// ------
// create a new Stock
var
apple
=
Stock
(
"AAPL"
,
1000
)
// search for a document with this symbol
query
=
MongoDBObject
(
"symbol"
->
"AAPL"
)
// replace the old document with the 'apple' instance
val
res2
=
collection
.
update
(
query
,
buildMongoDbObject
(
apple
))
println
(
"update: "
+
res2
)
}
In both cases, you build a document object to replace the existing
document in the database, and then create a query object, which lets you
find what you want to replace. Then you call either findAndModify
or update
to perform the update.
For instance, in the findAndModify
example, a new Stock
instance named google
is created, and it’s used to replace
the old document in the database whose symbol is GOOG
. The buildMongoDbObject
method is used to convert
the google
instance ...
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.