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 :

Connect

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(

              “mongodb://host1:27017,host2:27017,host3:27017”);

  • SSL Connect

How to connect over SSL

MongoClient mongoClient = MongoClients.create(

              mongodb://localhost/?streamType=netty&ssl=true);

  • Authenticated Connect

How to connect to a cluster with credentials

MongoClient mongoClient = MongoClients.create(

              mongodb://user1:pwd1@host1/?authSource=db1);

  • 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

      database.createCollection(“cappedCollection”,

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

          callbackWhenFinished);

  • 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

       collection.find(

    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”)))

                .sort(Sorts.ascending(“name”))

                .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.

https://docs.mongodb.com/manual/reference/read-concern/
  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”, “cafeconleche@example.com”)

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

               .append(“stars”, 3)

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

collection.insertOne(document)

  1. Bulk write to a Collection

Doing multiple rites in single command

       collection.bulkWrite(

  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

       collection.updateOne(

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

                combine(set(“stars”, 1),

                        set(“contact.phone”, “228-555-9999”),

                        currentDate(“lastModified”))

  1. Deleting from a Collection

Deleting from a collection

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

  1. Aggregating data from a Collection

                        collection.aggregate(Arrays.asList(

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

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

  1. Watching a Collection

Change streams provide a way to watch changes to documents in a collection.

       collection.watch().forEach(printBlock, callbackWhenFinished);

database.watch().forEach(printBlock, callbackWhenFinished);

  1. Searching a Collection

Searching a collection

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

                       .projection(Projections.metaTextScore(“score”))

                       .sort(Sorts.metaTextScore(“score”))

  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.

http://mongodb.github.io/mongo-java-driver/3.10/driver-async/tutorials/gridfs/

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

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