Insert Documents
On this page
Overview
In this guide, you can learn how to use the Scala driver to add documents to a MongoDB collection by performing insert operations.
An insert operation inserts one or more documents into a MongoDB collection. You can perform an insert operation by using the following methods:
insertOne()
to insert a single documentinsertMany()
to insert one or more documents
Sample Data
The examples in this guide use the restaurants
collection in the sample_restaurants
database from the Atlas sample datasets. To access this collection
from your Scala application, create a MongoClient
that connects to an Atlas cluster
and assign the following values to your database
and collection
variables:
val database: MongoDatabase = mongoClient.getDatabase("sample_restaurants") val collection: MongoCollection[Document] = database.getCollection("restaurants")
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.
The _id Field
In a MongoDB collection, each document must contain an _id
field
with a unique field value.
MongoDB allows you to manage this field in two ways:
Set the
_id
field for each document yourself, ensuring each value is unique.Let the driver automatically generate unique
BsonObjectId
values for each document_id
field.
Unless you can guarantee uniqueness, we recommend
letting the driver automatically generate _id
values.
Note
Duplicate _id
values violate unique index constraints, which
causes the driver to return an error.
To learn more about the _id
field, see the
Unique Indexes guide in the MongoDB Server manual.
To learn more about document structure and rules, see the Documents guide in the MongoDB Server manual.
Insert One Document
To add a single document to a MongoDB collection, call the insertOne()
method and pass the document you want to insert.
The following example inserts a document into the restaurants
collection:
val doc: Document = Document("name" -> "Neighborhood Bar & Grill", "borough" -> "Queens") val observable: Observable[InsertOneResult] = collection.insertOne(doc) observable.subscribe(new Observer[InsertOneResult] { override def onNext(result: InsertOneResult): Unit = println(result) override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage) override def onComplete(): Unit = println("Completed") })
AcknowledgedInsertOneResult{insertedId=BsonObjectId{value=...}} Completed
Insert Multiple Documents
To add multiple documents to a MongoDB collection, call the insertMany()
function and pass a list of documents you want to insert.
The following example inserts two documents into the restaurants
collection:
val docs: Seq[Document] = Seq( Document("name" -> "Metropolitan Cafe", "borough" -> "Queens"), Document("name" -> "Yankee Bistro", "borough" -> "Bronx") ) val observable: Observable[InsertManyResult] = collection.insertMany(docs) observable.subscribe(new Observer[InsertManyResult] { override def onNext(result: InsertManyResult): Unit = println(result) override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage) override def onComplete(): Unit = println("Completed") })
AcknowledgedInsertManyResult{insertedIds={0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}}} Completed
Modify Insert Behavior
The insertOne()
method optionally accepts an InsertOneOptions
parameter that sets options to configure the insert operation.
If you don't specify any options, the driver performs the insert
operation with default settings. Pass options as the last parameter to
the insertOne()
method.
The following table describes the setter methods that you can use to
configure an InsertOneOptions
instance:
Method | Description |
---|---|
| If set to true , allows the driver to ignore
document-level validation.Defaults to false . |
| Sets a comment to attach to the operation. For more information, see the insert command
fields guide in the
MongoDB Server manual for more information. |
You can set the preceding settings on the insertMany()
method
by configuring an InsertManyOptions
instance. You can also use the
ordered()
setter method to specify the order in which the driver
inserts documents into MongoDB. Pass options as the last parameter to the insertMany()
method.
Example
The following code uses the insertMany()
method to insert
three new documents into a collection. Because the bypassDocumentValidation
option is enabled, this insert operation bypasses document-level validation:
val docs: Seq[Document] = Seq( Document("name" -> "One Night's Delight", "borough" -> "Queens"), Document("name" -> "Second Street Pub", "borough" -> "Manhattan"), Document("name" -> "Triple Crown Diner", "borough" -> "Brooklyn") ) val opts: InsertManyOptions = InsertManyOptions().bypassDocumentValidation(true) val observable: Observable[InsertManyResult] = collection.insertMany(docs, opts) observable.subscribe(new Observer[InsertManyResult] { override def onNext(result: InsertManyResult): Unit = println(result) override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage) override def onComplete(): Unit = println("Completed") })
AcknowledgedInsertManyResult{insertedIds={0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}, 2=BsonObjectId{value=...}}} Completed
Additional Information
To learn more about any of the methods discussed in this guide, see the following API documentation: