Lesson 2: Inserting a Document in Java Applications / Learn

Video Transcript (English)

Hello!

In this video, you’ll learn how to use the insertOne() and insertMany() methods to create single documents and perform bulk write operations in MongoDB with a Java application.

We use the insertOne() method to insert a single document into a MongoDB collection. Let’s look at this in action.

First, we’ll create a new document in the inspections collection of the sample_training database.

The document has the structure shown here.

Notice that the sample document contains an embedded document. MongoDB recommends that you use embedded documents when you model your document schema.

We instantiate a Document instance that represents the BSON document.

We then initialize the various fields and values by using the Document class’s append method. The document has _id, date, and address fields, among others.

MongoDB documents have an _id field that uniquely identifies each document in a collection. We can think of this as being equivalent to a primary key. We can either provide a value for the _id field or the driver will generate the _id value for us.

Now we’re ready to insert our document. We’ll do this by invoking the insertOne method of the MongoCollection instance.

The MongoCollection interface creates a collection object. For brevity, we’ll assume that the MongoCollection instance and MongoClient have already been initialized.

The insertOne method returns an InsertOneResult, which gives us access to the _id of the inserted document.

Next, we’ll demonstrate how to use insertMany(). We’ll keep the document schema simple. This schema only has four fields: account_id, account_holder, account_type, and balance.

Let’s say we have 2 documents that we want to insert in our collection. We need to initialize the documents with the relevant field names and values.

After we initialize the documents, we add them to an accounts ArrayList. We then pass the accountsArrayList to the insertMany() method of the MongoCollection object. The insertMany method returns a InsertManyResults object. Lists are usually easier to manipulate than iterators.

To retrieve the Ids of the inserted documents, we use the getInsertedIds() method of the InsertManyResult object.

Well done! 

You now know how to use the insertOne() and insertMany() methods to create single documents and multiple documents in your MongoDB collection.