Insert Multiple Documents in MongoDB Java

In this example, We will show you simple program about, How to insert multiple documents in MongoDB java. The example were tested with mongodb server 3.4.2 environment and output shared in the same post.

Test Input Data

[
{
"_id":101,
"name":"John",
"age":25,
"qualification":"MS"
},
{
"_id":102,
"name":"Smith",
"age":27,
"qualification":"MBA"
},
{
"_id":103,
"name":"William",
"age":24,
"qualification":"MTech"
},
{
"_id":104,
"name":"Dinesh",
"age":26,
"qualification":"MCA"
},
{
"_id":105,
"name":"Peter",
"age":28,
"qualification":"MSc"
}
]

Example Program

package com.dineshkrish.mongo;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
/**
* 
* @author Dinesh Krishnan
*
*/
public class InsertMultipleDocuments {
public static void main(String[] args) {
// getting the connection
MongoClient client = new MongoClient("localhost", 27017);
// selecting the database
MongoDatabase database = client.getDatabase("dineshkrish");
// selecting the collections
MongoCollection<Document> collection = database.getCollection("employee_records");
// defining list object
List<Document> documentList = new ArrayList<Document>();
// document 1
Document document1 = new Document();
document1.put("_id", 101);
document1.put("name", "John");
document1.put("age", 25);
document1.put("qualification", "MS");
// document 2
Document document2 = new Document();
document2.put("_id", 102);
document2.put("name", "Smith");
document2.put("age", 27);
document2.put("qualification", "MBA");
// document 3
Document document3 = new Document();
document3.put("_id", 103);
document3.put("name", "William");
document3.put("age", 24);
document3.put("qualification", "MTech");
// document 4
Document document4 = new Document();
document4.put("_id", 104);
document4.put("name", "Dinesh");
document4.put("age", 26);
document4.put("qualification", "MCA");
// document 5
Document document5 = new Document();
document5.put("_id", 105);
document5.put("name", "Peter");
document5.put("age", 28);
document5.put("qualification", "MSc");
// adding all documents in to list object
documentList.add(document1);
documentList.add(document2);
documentList.add(document3);
documentList.add(document4);
documentList.add(document5);
// inserting the document list
collection.insertMany(documentList);
// closing the connection
client.close();
}
}

Output

How to Insert Multiple Documents in MongoDB Java

Referneces

1. MongoDB Java API Documentation
2. JavaDoc – MongoClient Class
3. JavaDoc – MongoDatabase Interface
4. JavaDoc – Document Class
5. JavaDoc – List Interface
6. JavaDoc – ArrayList Class

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *