Docs Menu
Docs Home
/ / /
Scala
/

Insert Documents

On this page

  • Overview
  • Sample Data
  • The _id Field
  • Insert One Document
  • Insert Multiple Documents
  • Modify Insert Behavior
  • Example
  • Additional Information

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 document

  • insertMany() to insert one or more documents

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.

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.

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

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

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

bypassDocumentValidation()

If set to true, allows the driver to ignore document-level validation.
Defaults to false.

comment()

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.

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

To learn more about any of the methods discussed in this guide, see the following API documentation:

Back

Write Data