Insert Documents

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

Insert Documents

Overview

In this guide, you can learn how to use the Java Reactive Streams 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 insertOne() or insertMany() methods.

Sample Data

The examples in this guide use the sample_restaurants.restaurants collection from the Atlas sample datasets.

To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the [Get Started](https://www.mongodb.com/docs/languages/java/reactive-streams-driver/current/getting-started.md#std-label-java-rs-getting-started tutorial.

Important: Project Reactor Library

This guide uses the Project Reactor library to consume Publisher instances returned by the Java Reactive Streams driver methods. To learn more about the Project Reactor library and how to use it, see [Getting Started](https://projectreactor.io/docs/core/release/reference/#getting-started in the Reactor documentation. To learn more about how we use Project Reactor library methods in this guide, see the [Write Data to MongoDB](https://www.mongodb.com/docs/languages/java/reactive-streams-driver/current/crud.md#std-label-write-data-reactor-overview 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:

  • You can set this field for each document yourself, ensuring each _id field value is unique.

  • You can let the driver automatically generate unique ObjectId values for each document _id. If you do not manually set an _id value for a document, the driver populates the field with an ObjectId.

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 a WriteError from insertOne() or a BulkWriteError from insertMany().

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 add. Then, pass the insertOne() result to the static Mono.from() method from Mono. Mono is a class from the Project Reactor library. In Java Reactive Streams, the driver methods return cold Publisher instances, which means that the corresponding operation does not happen unless you subscribe to the returned Publisher. This guide uses the Project Reactor library to consume them. To learn more about Mono, see [Mono](https://projectreactor.io/docs/core/release/reference/#mono in the Project Reactor documentation.

The following example uses the insertOne() method to insert a document in which the name value is “Mongo's Burgers“ into the restaurants collection:

 Document document = new Document("name", "Mongo's Burgers");
 Publisher<InsertOneResult> insertPublisher = restaurants.insertOne(document);
 Mono.from(insertPublisher).block();

Insert Multiple Documents

To add multiple documents to a MongoDB collection, call the insertMany() method and pass a list of documents you want to add. Then, pass the insertMany() result to the static Mono.from() method from Mono. Mono is a class from the Project Reactor library. In Java Reactive Streams, the driver methods return cold Publisher instances, which means that the corresponding operation does not happen unless you subscribe to the returned Publisher. This guide uses the Project Reactor library to consume them. To learn more about Mono, see [Mono](https://projectreactor.io/docs/core/release/reference/#mono in the Project Reactor documentation.

The following example uses the insertMany() method to insert a list of documents into the restaurants collection:

 Document doc1 = new Document("name", "Mongo's Pizza");
 Document doc2 = new Document("name", "Mongo's Coffee");

 List<Document> documents = Arrays.asList(doc1, doc2);

 Publisher<InsertManyResult> insertPublisher = restaurants.insertMany(documents);
 Mono.from(insertPublisher).block();

Modify Insert Behavior

The InsertOneOptions class contains methods that modify the behavior of the insertOne() method. To use the InsertOneOptions class, construct a new instance of the class, then call one or more of its methods to modify the insert operation. You can chain these method calls together. To modify the behavior of the insert operation, pass the class instance and chained method calls as the second argument to the insertOne() method.

You can similarly modify the insertMany() method by using the InsertManyOptions class.

You can use the following methods in the InsertOneOptions class to modify the insertOne() method. All methods are optional.

Method Description
bypassDocumentValidation (Boolean bypassDocumentValidation) If set to True, allows the write to opt out of document-level validation.Defaults to False.
toString() If used, returns a string representation of the object.
comment(BsonValue comment) A comment to attach to the operation. For more information, see the [insert command fields](https://www.mongodb.com/docs/manual/reference/command/insert/#command-fields guide in the MongoDB Server manual.

The InsertManyOptions class contains the previous methods, as well as the following ordered() method:

Method Description
ordered(Boolean ordered) If set to True, the driver sends documents to the server in the order provided. If an error occurs, the driver and server cancel all remaining insert operations.Defaults to True.

Example

The following code uses the insertMany() method to insert new documents into the restaurants collection. It also sets the bypassDocumentValidation(true) option to bypass document-level validation.

 Document doc1 = new Document("name", "Mongo's Burgers");
 Document doc2 = new Document("name", "Mongo's Pizza");
 Document doc3 = new Document("name", "Mongo's Coffee");

 List<Document> documents = Arrays.asList(doc1, doc2, doc3);

Publisher<InsertManyResult> insertPublisher =
        restaurants.insertMany(documents,
                new InsertManyOptions().bypassDocumentValidation(true));

 Mono.from(insertPublisher).block();

Additional Information

For runnable code examples of inserting documents with the Java Reactive Streams driver, see the [CRUD Operations](https://www.mongodb.com/docs/languages/java/reactive-streams-driver/current/crud.md#std-label-java-rs-write guide.

API Documentation

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

  • [insertOne()](https://mongodb.github.io/mongo-java-driver/5.13/apidocs/driver-reactive-streams/com/mongodb/reactivestreams/client/MongoCollection.html#insertOne(com.mongodb.reactivestreams.client.ClientSession,TDocument)

  • [insertMany()](https://mongodb.github.io/mongo-java-driver/5.13/apidocs/driver-reactive-streams/com/mongodb/reactivestreams/client/MongoCollection.html#insertMany(com.mongodb.reactivestreams.client.ClientSession,java.util.List)

  • InsertOneOptions

  • InsertManyOptions

  • BsonValue