Using Java client to interact with MongoDB

The official MongoDB Java Driver provides both synchronous and asynchronous interaction with MongoDB.

Following are the operations supported in MongoDB :


How to connect to a mongodb server

MongoClient mongoClient = MongoClients.create(“mongodb://host1:27017”);

  • Cluster Connect

How to connect to a cluster of mongo dbs

MongoClient mongoClient = MongoClients.create(


  • SSL Connect

How to connect over SSL

MongoClient mongoClient = MongoClients.create(


  • Authenticated Connect

How to connect to a cluster with credentials

MongoClient mongoClient = MongoClients.create(


  • Compression

Compression of messages to and from MongoDB servers

MongoClient mongoClient = MongoClients.create(“mongodb://localhost/?compressors=zlib/snappy”);

  • Creating database

Specify the name of the database to the getDatabase() method. If a database does not exist, MongoDB creates the database when you first store data for that database.

MongoDatabase database = mongoClient.getDatabase(“test”);

  • Creating Collection

Creating a collection inside a database


          new CreateCollectionOptions().capped(true).sizeInBytes(0x100000),


  • Reading Collection

Read from a collection

       collection.find(eq(“name”, “456 Cookies Shop”))

            .forEach(printBlock, callbackWhenFinished);

  • Reading Collection with Filters

Reading from collection based on filters


    new Document(“stars”, new Document(“$gte”, 2)

          .append(“$lt”, 5))

          .append(“categories”, “Bakery”)).forEach(printBlock, callbackWhenFinished);

  1. Reading Sorted Collection

Sort the data

      collection.find(and(gte(“stars”, 2), lt(“stars”, 5), eq(“categories”, “Bakery”)))


                .forEach(printBlock, callbackWhenFinished);

  1. Reading Collection with concerns

The readConcern option allows you to control the consistency and isolation properties of the data read from replica sets and replica set shards.
  1. Writing to a Collection

To insert the document into the collection, you can use the collection’s insertOne() method.

Document document = new Document(“name”, “Café Con Leche”)

               .append(“contact”, new Document(“phone”, “228-555-0149”)

                                       .append(“email”, “”)

                                       .append(“location”,Arrays.asList(-73.92502, 40.8279556)))

               .append(“stars”, 3)

               .append(“categories”, Arrays.asList(“Bakery”, “Coffee”, “Pastries”));


  1. Bulk write to a Collection

Doing multiple rites in single command


  Arrays.asList(new InsertOneModel<>(new Document(“_id”, 4)),

                new InsertOneModel<>(new Document(“_id”, 5)),

                new InsertOneModel<>(new Document(“_id”, 6)),

                new UpdateOneModel<>(new Document(“_id”, 1),

                                     new Document(“$set”, new Document(“x”, 2))),

                new DeleteOneModel<>(new Document(“_id”, 2)),

                new ReplaceOneModel<>(new Document(“_id”, 3),

                                      new Document(“_id”, 3).append(“x”, 4))),

  1. Updating a Collection

Updating a collection


                eq(“_id”, new ObjectId(“57506d62f57802807471dd41”)),

                combine(set(“stars”, 1),

                        set(“”, “228-555-9999”),


  1. Deleting from a Collection

Deleting from a collection

       collection.deleteOne(eq(“_id”, new ObjectId(“57506d62f57802807471dd41”))

  1. Aggregating data from a Collection


                        Aggregates.match(Filters.eq(“categories”, “Bakery”)),

              “$stars”, Accumulators.sum(“count”, 1))))

  1. Watching a Collection

Change streams provide a way to watch changes to documents in a collection., callbackWhenFinished);, callbackWhenFinished);

  1. Searching a Collection

Searching a collection

      collection.find(Filters.text(“bakery cafe”))



  1. Storing huge docs

GridFS is a specification for storing and retrieving files that exceed the BSON document size limit of 16MB. Instead of storing a file in a single document, GridFS divides a file into parts, or chunks, and stores each of those chunks as a separate document.

Uday Ogra

Connect with me at and lets have some healthy discussion :)

You may also like...

Leave a Reply

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