Objective and Prerequisites

Objective: This segment introduces implementation of how to insert and retrieve the documents from a collection in MongoDB using Java.

Prerequisites: MongoDB is setup installed and running in the background. Also, the project has been developed and executed in Eclipse IDE (Integrated Development Environment).

To run the following program, you need to download the MongoDB Java driver jar file Download MongoDB Java driver. Once downloaded, you can import the library by right-clicking on your project in Eclipse -> Properties -> Java Build Path -> Libraries -> Add External JARs...

Start MongoDB (running mongo.exe)
MongoDB shell version v4.2.3
connecting to: mongodb://127.0.0.1:27017/
MongoDB server version: 4.2.3

> show dbs
DB      0.000GB
admin   0.000GB
config  0.000GB
local   0.000GB

> use DB
switched to db DB

> db.getCollectionNames()
[ "holders" ]

> db.holders.find().pretty()
>
Java MongoDB to insert and retrieve the documents from a collection
Note: In the following program, database and collection automatically get created. If database and collection already exist in MongoDB, then new documents will get inserted into an existing collection.
KW.java
import java.util.ArrayList;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

class KW
{
    public static void main(String[] args)
    {
        try
        {
            MongoClient mc = new MongoClient("localhost", 27017);
            MongoDatabase md = mc.getDatabase("DB");
            MongoCollection<Document> collection = md.getCollection("holders");
            
            String document1,document2,document3,document4;
            document1="{ 'account_no' : 2562348989, 'name' : 'James Moore', 'city' : 'Phoenix', 'DOB' : ISODate('1985-05-26T00:00:00Z'), 'bank' : 'Barclays', 'amount' : 5000, 'loan' : [ { 'Personal' : 5660, 'Home' : 15000 } ] }";
            document2="{ 'account_no' : 2562348990, 'name' : 'Donald Taylor', 'city' : 'Irvine', 'DOB' : ISODate('1990-08-20T00:00:00Z'), 'bank' : 'Citi', 'amount' : 7000, 'loan' : [ { 'Home' : 10000, 'Car' : 20000 } ] }";
            document3="{ 'account_no' : 2562348991, 'name' : 'Edward Parkar', 'city' : 'Irvine', 'DOB' : ISODate('1994-01-29T00:00:00Z'), 'bank' : 'ICICI', 'amount' : 95000, 'loan' : [ { 'Personal' : 25000, 'Home' : 450000, 'Car' : 10000 } ] }";   
            document4="{ 'account_no' : 2562348992, 'name' : 'Ryan Bakshi', 'city' : 'Mumbai', 'DOB' : ISODate('1982-01-14T00:00:00Z'), 'bank' : 'Citi', 'amount' : 50000, 'loan' : [ { 'Personal' : null, 'Home' : null, 'Car' : null } ] }";
            
            Document d1,d2,d3,d4;
            d1=Document.parse(document1);
            d2=Document.parse(document2);
            d3=Document.parse(document3);
            d4=Document.parse(document4);
            
            collection.insertOne(d1);
            System.out.println("A document inserted successfully");
            
            ArrayList<Document> docs=new ArrayList<Document>();
            docs.add(d2);
            docs.add(d3);
            docs.add(d4);
            collection.insertMany(docs);
            System.out.println("Multiple documents inserted successfully");
            
            FindIterable<Document> fi=collection.find();
            MongoCursor<Document> cursor=fi.iterator();
            while(cursor.hasNext()) 
            {
                System.out.println(cursor.next());
            }
            mc.close();
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}
Output
A document inserted successfully
Multiple documents inserted successfully
Document{{_id=5e7c41de4ed7527e8c863ff7, account_no=2562348989, name=James Moore, city=Phoenix, DOB=Sun May 26 05:30:00 IST 1985, bank=Barclays, amount=5000, loan=[Document{{Personal=5660, Home=15000}}]}}
Document{{_id=5e7c41df4ed7527e8c863ff8, account_no=2562348990, name=Donald Taylor, city=Irvine, DOB=Mon Aug 20 05:30:00 IST 1990, bank=Citi, amount=7000, loan=[Document{{Home=10000, Car=20000}}]}}
Document{{_id=5e7c41df4ed7527e8c863ff9, account_no=2562348991, name=Edward Parkar, city=Irvine, DOB=Sat Jan 29 05:30:00 IST 1994, bank=ICICI, amount=95000, loan=[Document{{Personal=25000, Home=450000, Car=10000}}]}}
Document{{_id=5e7c41df4ed7527e8c863ffa, account_no=2562348992, name=Ryan Bakshi, city=Mumbai, DOB=Thu Jan 14 05:30:00 IST 1982, bank=Citi, amount=50000, loan=[Document{{Personal=null, Home=null, Car=null}}]}}
MongoDB Instance
> db.holders.find().pretty()
{
    "_id" : ObjectId("5e7c41de4ed7527e8c863ff7"),
    "account_no" : NumberLong("2562348989"),
    "name" : "James Moore",
    "city" : "Phoenix",
    "DOB" : ISODate("1985-05-26T00:00:00Z"),
    "bank" : "Barclays",
    "amount" : 5000,
    "loan" : [
        {
            "Personal" : 5660,
            "Home" : 15000
        }
    ]
}
{
    "_id" : ObjectId("5e7c41df4ed7527e8c863ff8"),
    "account_no" : NumberLong("2562348990"),
    "name" : "Donald Taylor",
    "city" : "Irvine",
    "DOB" : ISODate("1990-08-20T00:00:00Z"),
    "bank" : "Citi",
    "amount" : 7000,
    "loan" : [
        {
            "Home" : 10000,
            "Car" : 20000
        }
    ]
}
{
    "_id" : ObjectId("5e7c41df4ed7527e8c863ff9"),
    "account_no" : NumberLong("2562348991"),
    "name" : "Edward Parkar",
    "city" : "Irvine",
    "DOB" : ISODate("1994-01-29T00:00:00Z"),
    "bank" : "ICICI",
    "amount" : 95000,
    "loan" : [
        {
            "Personal" : 25000,
            "Home" : 450000,
            "Car" : 10000
        }
    ]
}
{
    "_id" : ObjectId("5e7c41df4ed7527e8c863ffa"),
    "account_no" : NumberLong("2562348992"),
    "name" : "Ryan Bakshi",
    "city" : "Mumbai",
    "DOB" : ISODate("1982-01-14T00:00:00Z"),
    "bank" : "Citi",
    "amount" : 50000,
    "loan" : [
        {
            "Personal" : null,
            "Home" : null,
            "Car" : null
        }
    ]
}
Advertisement