Basic CRUD Operations on MongoDB + Java

crudmongodb

In previous Post , we have seen 5 ways to connect to Mongo DB , now perform CRUD operations on Mongo DB using Java Driver 3.2.

Dependency Needed:

<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.0.4</version>
    </dependency>
</dependencies>

Add the above dependency in the maven project.

To Insert One Document

Document doc = new Document("name", "dilip")
                .append("email", "dilip@gmail.com")
                .append("password", "secreat")
                .append("address", new Document("steet", "zyx").append("city", "somecity").append("country", "india"));

collection.insertOne(doc);

To Insert Multiple Document

 List<Document> docList = new ArrayList<Document>();
        for (int i = 0; i < 10; i++) {
            docList.add(new Document("i" , i));
        }
        collection.insertMany(docList);

To get the count of documents present in the Collection

 long count = collection.count();
 System.out.println("Total documents in collection is ::"+ count);

To get All the documents present in the Collection

MongoCursor<Document> cursor = collection.find().iterator();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }

Note: the find() methods returns all the documents, and we need to iterate through the documents using the iterator.

To update document in a collection

collection.updateOne(Filters.eq("i", 10),
         new Document("$set", new Document("i", 110)));

Note: the above code,update the first document that has the i value as 10. if you want to update all the documents to be updated you can use

updateMany()

Lest see the full Example

import com.mongodb.CursorType;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.UpdateResult;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;

public class MongoCrud {

    public static void main(String[] args) {

        // Connect to database

        MongoClient mongoClient = new MongoClient("localhost");
        MongoDatabase database = mongoClient.getDatabase("test");

        // get collection
        MongoCollection collection = database.getCollection("user");

        // To insert one docuemnt
        Document doc = new Document("name", "dilip")
                .append("email", "dilip@gmail.com")
                .append("password", "secreat")
                .append("address", new Document("steet", "zyx").append("city", "somecity").append("country", "india"));

//         collection.insertOne(doc);

        // to insert many docuements
        List<Document> docList = new ArrayList<Document>();
        for (int i = 0; i < 10; i++) {
            docList.add(new Document("i" , i));
        }
        collection.insertMany(docList);

        // to Count the number of documents in collection
        long count = collection.count();
        System.out.println("Total documents in user is ::"+ count);

        // get the first document
        Document firstDoc = (Document) collection.find().first();

        // get All Documents
        MongoCursor<Document> cursor = collection.find().iterator();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }

        UpdateResult result =  collection.updateOne(Filters.eq("i", 10), new Document("$set", new Document("i", 110)));

    }
}

References:
http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/

Advertisements

About sivateja

I am a professional graduate..I am passionate about Latest Technology.
This entry was posted in mongodb and tagged , , , . Bookmark the permalink.

One Response to Basic CRUD Operations on MongoDB + Java

  1. Pingback: SELECT vs FIND() [search records in Mongo way] – SivaPulse

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s