16.4. Inserting Documents into MongoDB with insert, save, or +=
Problem
You want to save documents to a MongoDB collection from a Scala application.
Solution
Use the insert
, save
, or +=
methods of the Casbah MongoCollection
class.
In order to save a document to your MongoDB collection, you can
use the MongoCollection insert
method:
collection
.
insert
(
buildMongoDbObject
(
apple
))
collection
.
insert
(
buildMongoDbObject
(
))
collection
.
insert
(
buildMongoDbObject
(
netflix
))
You can also use the save
method:
collection
.
save
(
buildMongoDbObject
(
apple
))
collection
.
save
(
buildMongoDbObject
(
))
collection
.
save
(
buildMongoDbObject
(
netflix
))
And you can also use the +=
method:
collection
+=
buildMongoDbObject
(
apple
)
collection
+=
buildMongoDbObject
(
)
collection
+=
buildMongoDbObject
(
netflix
)
collection
+=
buildMongoDbObject
(
amazon
)
The intention of the insert
and
save
methods is obvious; you’re
inserting/saving data to your MongoDB collection. The third approach is
a little different; it looks like what you’re doing is adding an object
to a collection. In fact, you’re saving your object to the database
collection with each +=
call.
Here’s what the +=
approach
looks like in a complete program:
import
com.mongodb.casbah.Imports._
import
Common._
object
Insert2
extends
App
{
val
collection
=
MongoFactory
.
collection
// create some Stock instances
val
apple
=
Stock
(
"AAPL"
,
600
)
val
=
Stock
(
"GOOG"
,
650
)
val
netflix
=
Stock
(
"NFLX"
,
60
)
val
amazon
=
Stock
(
"AMZN"
,
220
)
// add them to the collection ...
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.