Docs Home → Develop Applications → MongoDB Drivers → Java
Insert Operations
Overview
In this guide, you can learn how to insert documents with the MongoDB Java driver.
You can use MongoDB to retrieve, update, and delete information. To perform any of those operations, that information, such as user profiles and orders, needs to exist in MongoDB. For that information to exist, you need to first perform an insert operation.
An insert operation inserts a single or multiple documents into MongoDB
using the insertOne()
, insertMany()
, and bulkWrite()
methods.
The following sections focus on insertOne()
and
insertMany()
. For information on how to use the bulkWrite()
method, see our
guide on Bulk Operations.
A Note About _id
When inserting a document, MongoDB enforces one constraint on your
documents by default: each document must contain a unique _id
field.
There are two ways to manage this field:
You can manage this field yourself, ensuring each value you use is unique.
You can let the driver automatically generate unique ObjectId values.
Unless you have provided strong guarantees for uniqueness, we recommend
you let the driver automatically generate _id
values.
Note
Duplicate _id
values violate unique index constraints, resulting
in a WriteError
.
For additional information on unique indexes, see the manual entry on Unique Indexes.
Insert a Single Document
Use the insertOne()
method when you want to insert a single
document.
On successful insertion, the method returns an InsertOneResult
instance representing the _id
of the new document.
Example
The following example creates and inserts a document using the
insertOne()
method:
Document doc1 = new Document("color", "red").append("qty", 5); InsertOneResult result = collection.insertOne(doc1); System.out.println("Inserted a document with the following id: " + result.getInsertedId().asObjectId().getValue());
Your output should look something like this:
Inserted a document with the following id: 60930c39a982931c20ef6cd6
For more information about the methods and classes mentioned in this section, see the following resources:
insertOne() API Documentation
InsertOneResult API Documentation
Manual Explanation on insertOne()
Runnable Insert a Document Example
Insert Multiple Documents
Use the insertMany()
method when you want to insert multiple
documents. This method inserts documents in the order specified until an
exception occurs, if any.
For example, assume you want to insert the following documents:
{ "_id": 3, "color": "red", "qty": 5 } { "_id": 4, "color": "purple", "qty": 10 } { "_id": 3, "color": "yellow", "qty": 3 } { "_id": 6, "color": "blue", "qty": 8 }
If you attempt to insert these documents, a WriteError
occurs at the
third document and the documents prior to the error get inserted into
your collection.
Tip
Use a try-catch block to get an acknowledgment for successfully processed documents before the error occurs:
List<Integer> insertedIds = new ArrayList<>(); try { InsertManyResult result = collection.insertMany(documents); result.getInsertedIds().values() .forEach(doc -> insertedIds.add(doc.asInt32().getValue())); System.out.println("Inserted documents with the following ids: " + insertedIds); } catch(MongoBulkWriteException exception) { exception.getWriteResult().getInserts() .forEach(doc -> insertedIds.add(doc.getId().asInt32().getValue())); System.out.println("A MongoBulkWriteException occurred, but there are " + "successfully processed documents with the following ids: " + insertedIds); }
The output consists of documents MongoDB can process and should look something like this:
A MongoBulkWriteException occurred, but there are successfully processed documents with the following ids: [3, 4, 6]
If you look inside your collection, you should see the following documents:
{ "_id": 3, "color": "red", "qty": 5 } { "_id": 4, "color": "purple", "qty": 10 }
On successful insertion, the method returns an InsertManyResult
instance representing the _id
of each new document.
Example
The following example creates and adds two documents to a List
, and
inserts the List
using the insertMany()
method:
List<Document> documents = new ArrayList<>(); Document doc1 = new Document("color", "red").append("qty", 5); Document doc2 = new Document("color", "purple").append("qty", 10); documents.add(doc1); documents.add(doc2); InsertManyResult result = collection.insertMany(documents); List<ObjectId> insertedIds = new ArrayList<>(); result.getInsertedIds().values() .forEach(doc -> insertedIds.add(doc.asObjectId().getValue())); System.out.println("Inserted documents with the following ids: " + insertedIds);
Your output should look something like this:
Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, 60930c3aa982931c20ef6cd8]
For more information about the methods and classes mentioned in this section, see the following resources:
insertMany() API Documentation
InsertManyResult API Documentation
Manual Explanation on insertMany()
Runnable Insert Multiple Documents Example
Summary
There are three ways to perform an insert operation, but we focused on two:
The
insertOne()
method inserts a single document.The
insertMany()
method inserts multiple documents.
Both methods automatically generate an _id
if you omit the field in
your document.
If the insertion is successful, both methods return an instance
representing the _id
of each new document.