MongoDB Insert Document into Collection

In MongoDB learning series, we have already covered the MongoDB basics, MongoDB installation in Windows, and how to query/select documents from a collection. In this tutorial, I am listing multiple ways you can utilize to insert or add document(s) into a collection in MongoDB. 1. Sample Document to …

MongoDB_Logo

In MongoDB learning series, we have already covered the MongoDB basics, MongoDB installation in Windows, and how to query/select documents from a collection. In this tutorial, I am listing multiple ways you can utilize to insert or add document(s) into a collection in MongoDB.

1. Sample Document to Insert into Collection

For demo purposes, we will be using the following document structure to add to a collection.

{
    "name":"lokesh",
    "website":"howtodoinjava.com",
    "address":{
        "addressLine1":"Some address",
        "addressLine2":"Karol Bagh",
        "addressLine3":"New Delhi, India"
    }
}

2. insertOne(): Insert a Single Document

The insertOne() method is the simplest way to add a single document to a MongoDB collection. It’s part of the MongoDB Java Driver and is designed to insert one document at a time.

In this example, a document containing the fields name, website, and a nested address object is inserted into the users collection.

try (var mongoClient = MongoClients.create("mongodb://localhost:27017")) {

  MongoDatabase database = mongoClient.getDatabase("testdb");
  MongoCollection<Document> collection = database.getCollection("users");

  Document doc = new Document("name", "lokesh")
    .append("website", "howtodoinjava.com")
    .append("address", new Document("addressLine1", "Some address")
      .append("addressLine2", "Karol Bagh")
      .append("addressLine3", "New Delhi, India"));

  collection.insertOne(doc);
  System.out.println("Document inserted successfully!");
}

3. insertMany(): Insert Multiple Documents

The insertMany() method allows us to insert multiple documents in a single operation, making it more efficient for batch operations.

Here’s how we can use insertMany() to insert multiple documents:

List<Document> documents = Arrays.asList(

    new Document("name", "lokesh")
        .append("website", "howtodoinjava.com")
        .append("address", new Document("addressLine1", "Some address")
                .append("addressLine2", "Karol Bagh")
                .append("addressLine3", "New Delhi, India")),

    new Document("name", "Alex")
        .append("website", "website.com")
        .append("address", new Document("addressLine1", "Some other address")
                .append("addressLine2", "...")
                .append("addressLine3", "..."))
);

collection.insertMany(documents);
System.out.println("Multiple documents inserted successfully!");

By default, insertMany() preserves the order of documents during insertion. We can disable this behavior to improve performance by setting the ordered parameter to false:

InsertManyOptions options = new InsertManyOptions().ordered(false);
collection.insertMany(documents, options);

4. Upsert Operations

Upsert (update or insert) operations are useful when you want to insert a document if it doesn’t exist or update it if it does. This is done using replaceOne() with upsert=true.

In the following example, if a document with _id 1 exists, it will be updated. Otherwise, a new document will be inserted.

collection.replaceOne(
    Filters.eq("_id", 1),
    new Document("_id", 1).append("name", "lokesh")
        .append("website", "howtodoinjava.com")
        .append("address", new Document("addressLine1", "Some address")
                .append("addressLine2", "Karol Bagh")
                .append("addressLine3", "New Delhi, India")),
    new ReplaceOptions().upsert(true)
);

5. Managing Transactions for Inserts

Transactions allow you to group multiple operations into a single unit of work. They ensure atomicity, consistency, isolation, and durability (ACID).

In the following example, if any operation fails, the transaction is aborted, and all changes are rolled back.

ClientSession session = mongoClient.startSession();

session.startTransaction();
try {
    MongoCollection<Document> coll = database.getCollection("orders");

    coll.insertOne(session, new Document("name", "lokesh")
            .append("website", "howtodoinjava.com")
            .append("address", new Document("addressLine1", "Some address")
                    .append("addressLine2", "Karol Bagh")
                    .append("addressLine3", "New Delhi, India")));

    coll.insertOne(session, new Document("name", "alex")
            .append("website", "example.com")
            .append("address", new Document("addressLine1", "Some other address")
                    .append("addressLine2", "...")
                    .append("addressLine3", "...")));

    session.commitTransaction();
    System.out.println("Transaction committed successfully!");
} catch (Exception e) {
    session.abortTransaction();
    System.out.println("Transaction aborted due to an error: " + e.getMessage());
}

6. Summary

In this guide for MongoDB insert statements, we explored:

  • Using insertOne() for inserting single documents
  • Inserting multiple documents with insertMany() and handling edge cases
  • Upsert operations to update or insert documents
  • Leveraging transactions for atomic insert operations

Happy Learning !!

Leave a Comment

  1. good examples .. i am trying to use the 2nd concept (Use DBObjectBuilder to insert document in collection ) to build and test sample applications. Able to insert the records during the first trigger call from java but if changing the record data and try to insert the MongoDB documents are not getting inserted again with the changed data.

    Please suggest.

    Reply
  2. hey i want to write a program in java to insert data from csv file, xml file, excel file into mongodb. Plz help me how would….

    Reply
  3. how to get id object of a particular collection by mapping first name. I have user collection and user attendance collections. I already created all users and their details as user collection, now i need to create another collection in the same db but now i want to put same _id object to the new collection according to same name its mean same person which i have inserted to the user collection.
    i thought you can help me..
    best regards
    one of your student (through your posts)

    Reply
  4. Thanks for providing such a nice example. I wonder it should be done using Spring “org.springframework.data.mongodb.core”. Could you please post example on this too?

    Reply
  5. Thanks for the above tutorial.

    How ever, i am trying to insert into an embedded document in a loop. When I use collection.update(), the previously inserted embedded document gets overwritten by the new document. My document structure is

    Key_1: Value_1
    Key_2: {
    A1:B1
    A2:B2
    A3:B3
    }

    Keys A1, A2 and A3 gets inserted in a loop along with their values. The issue I am facing is, everytime A1:B1 gets overwritten by A2:B2 and then end of update, database only has A3:B3. What is the way to insert all three in a loop so that it does not override the previous one? Can you please show how to do it in Java?

    Reply

Leave a Comment

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.