Getting started with MongoDB


Hello Everyone,

In this post, I am going to present some of the basic syntax and example of MongoDB to get started with it. For basic detail of NoSQL db visit this link.

What is MongoDB?

Mongo db is an open source, cross-platform NoSql database. It is a document-oriented db which is written in C++.

Mongo db stores its data on the filesystem. It stores all the data in BSON (Binary JSON). The format of BSON documents is very similar to the Object Oriented Programming. In MongoDB we can store complete information in one document rather than creating different tables for them and then define a relationship between them.

Let’s take a brief look at terms which mongo db uses to store the data:

  • Collections: You need to create collections in each Database. Each DB can contain multiple collections.
  • Documents: Each Collection contains multiple Documents.
  • Fields: Each Document contains multiple Fields.


Now get started with the commands:


  • Create db or Use db: There is no command to create a db in Mongo. Whenever we want to create a new db use following command.
    • Syntax: use <dbname>
    • Example: use customerdb
  • Show current db : This is very simple and small command
    • Syntax: db
  • Show db : This command will return the existing dbs only if it contains at least one collection.
    • Syntax: show dbs

At this time we did show dbs it will return only a default db. For this, we need to add a collection to it. We will see how to add collection in collection section. But for now, presenting an example:

    • Example: db.customer({first_name:”Robin”}
    • show dbs

Now we can see our db customerdb in the list.

  • Drop db: To drop database following is the command. Before deleting database first select the db.
    • Syntax: db.dropDatabase()
    • Example: use customerdb


  • Create collection : Mongo db normally we do not need to create collection explicitly. When we write a command to insert the document it will create the collection if does not exist. But there is a way to create collection explicitly an define it as expected:
    • Syntax: db.createCollection(<collectionName>, option)
      db.createCollection(<name>, { capped: <boolean>,
      autoIndexId: <boolean>,
      size: <number>,
      max: <number>,
      storageEngine: <document>,
      validator: <document>,
      validationLevel: <string>,
      validationAction: <string>,
      indexOptionDefaults: <document>,
      viewOn: <string>,
      pipeline: <pipeline>,
      collation: <document> } )
    • Example: db.createCollection(customer)

Collection name’s type is String and option type is Document.
Some of the important fields I am describing below:

Field(optional) Type Description
capped boolean If it sets to true it creates capped collection. For capped collection we need to define the size as well.
size number It defines the size of the capped collection. If the documents size reached to its limit then on each insert mongo db started deleting the old entries.
max number This defines the max size of capped collection. If the size is defined less then max size mongo db will start deleting the old document. So we need to ensure that max size is always less then size.
autoIndexId boolean It automatically creates index on id.


  • Drop Collection: We can drop a collection by using the following index but before dropping any collection we should be in the same db.
    • Syntax: db.<collectionName>.drop()
    • Example: use customerdb

CRUD Operations:

Mongo db provides very flexibility for CRUD operations. We can insert or update document on the fly.

  • Insert Document:
    • Syntax: db.<collectionName>.insert(<documents>)
    • Example:  db.customer.insert([{first_name:”Robin”, last_name:”Desosa”}, {first_name:“Kanika”, last_name:”Bhatnagar”},{first_name:”Rakesh”, last_name:”Sharma”, gender:”male”}]);

In the above example we are adding 3 document, first 2 are having the same fields but the third document has an additional field gender. Mongo db provides a functionality to insert the non structural data.
When you insert a document mongo db will automatically create a unique Id for each document.

  • Update Document:
    • Syntax: db.<collectionName>.update({<documentIdentifier>}, {$set:{<update value>}})
    • Example: db.customer.update({first_name:”Robin”},  {$set:{gender:”male”}});
      db.customer.update({first_name:”Kanika”},  {$set:{gender:”female”}});db.customer.update({first_name:”Rakesh”}, {$set:{age:”25”}})The above example will add a new field in corresponding document.
  • Update or Insert: Upsert command updates the document if it already exists or inserts a new one.
    • Syntax: db.<collectionName>.upsert({<docIdentifier>}, {<document>}, {upsert:true})
    • Example: db.customer({first_name:”Amita”}, {first_name:” Amita”, last_name:”Jain”, gender:”female”}, {upsert: true});
  • Rename Field in Document: We can rename field of a specific document by using $rename in update command.
    • Syntax: db.<collectionName>. update({<documentIdentifier>}, {$rename:{<update value>}})
    • Example: db.customer.update({first_name:”Rakesh”}, {$rename:{“gender”:”sex”}});After this we renamed the gender field to sex only for the document whose first_name is “Rakesh”.
  • Remove a field: To remove a field $unset needs to be used in update command.
    • Syntax: db.<collectionName>.update({<documentIdentifier >}, {$unset:{<field:1>}})
    • Example: Db.customer.update({first_name:”Rakesh”}, {$unset:{age:1}});
  • Remove Document:
    • Syntax: db.<collectionName>.remove({<documentIdentifier >})
    • Example: db.customer.remove({first_name:”Amita”});
      (If we have multiple entries with first_name Amita and want to remove 1.)
      db.customer.remove({first_name:”Amita”}, {justOne:true});
  • Find Document: We can find the document in collection by using following command. The output of that command is an object in json form.
    • Syntax: db.<collectionName>.find()
    • Example: db.customer.find();

The output of the above command will be all the json object stored in that collection.
To see it in a formatted way like each object and field in new line we can use pretty on find.

Example: db.customer.find().pretty();

  • Find Specific: By passing the documentIdentifier value in find method.
    • Syntax: db.<collectionName>.find({<documentIdentifier >})
    • Example: db.customer.find({first_name:”Kanika”});
  • Or condition: 
    • Example: db.customer.find({$or:[{first_name:”Kanika”}, {first_name:”Robin”}]});

In the above example we have a document in find as parameter, and in that document we have give an array of first_name. $or is defining the operation which is going to be performed on the array.

  • Greater than, Less than: We can directly jump on the example of the greater than and less than.


  • db.customer.find({age:{$gt:26}});
    In the above example $gt defines that > operation need to be perform on age. It will find and print all the documents who has this field age and age >26.
  • db.customer.find({age:{$lt:26}});
    In the same way this $lt will help us to find all documents which have age field and age < 26.
  • db.customer.find({age:{$gte:26}});
    We can perform >= or <= operations as well by using $gte and $lte.

Following are some more example on features provided by Mongo db:

  • Sort:
    • db.customer.find().sort({first_name:1}); //descending order
      db.customer.find().sort({first_name:-1}); //ascending order
  • Count:
    • db.customer.find().count();
  • ForEach:
    • db.customer.find().forEach(function(doc){print(“Customer Name:”+ doc.first_name)});

These all are the basic syntax for getting started with MongoDb.






Delegates in Kotlin

Hi Everyone,

Today we gonna discuss delegates in kotlin.

The Delegation pattern has proven to be a good alternative to implementation inheritance, and kotlin supports it natively requiring zero boilerplate code.

Property delegates don’t have to implement any interface, but they have to provide a getValue() and setValue() function.

let’s see an example, that mention in Kotlin ref docs. going to define Delegate class with getValue and setValue function.

class Delegate {

    operator fun getValue(thisRef : Any?, property : KProperty<*>) : String
        return "${thisRef?.javaClass?.name}, thank you for delegating '${}' to me!"

    operator fun setValue(thisRef : Any?, property : KProperty<*>,value : String)
        println("$value has been assigned to '${}' in ${thisRef?.javaClass?.name}.")

now creating another class.

class Example {
     var p : String by Delegate()

call Example class

fun main(args : Array)
    var example = Example()
    example.p = "delegate world"

com.delegated.Example, thank you for delegating 'p' to me!
delegate world has been assigned to 'p' in com.delegated.Example.

kotlin provides few delegated properties build into the language – Lazy properties, Observable properties, and properties storing in the map.

Lazy Properties: lazy is a function that takes a lambda and returns and returns an instance of Lazy which can serve as a delegate.

let’s create an example class.

class Example {
     val lazyValue: String by lazy {
fun main(args : Array)

Observable properties: Observable takes two arguments: the initial value and a handle for modifications. the handler gets called every time we assign the property. it has three parameters: a property being assigned to, the old value and the new one.

let’s create an example class

class Example {
     var name: String by Delegates.observable("") {
          prop, old, new ->
          println("$old -> $new")
fun main(args : Array)
    var example = Example() = "first" = "second"
 -> first
first -> second

Properties storing in the map: One common use case is storing the values of properties in a map. This comes up often in applications like parsing JSON or doing other “dynamic” things. In this case, you can use the map instance itself as the delegate for a delegated property.

let’s create an example class.

class User(val map: Map<String, Any?>) {
    val name:String by map
    val age: Int by map
fun main(args : Array)
    var user = User(mapOf("name" to "Ritesh pathak", "age" to 23))
Ritesh pathak

Ref – Kotlin docs.

Hope you like this. Thanks for reading 🙂

Java to Kotlin part -2

Hello Everyone,

In this post, we will see object-oriented syntex and features in Kotlin. for other basic detail please visit the part-1 tutorial to make yourself comfortable.

let’s jump into code!

#using class


class Customer {


class Customer {
//or if the class has no body then curley braces can be omitted
class Customer


#using constructor including primary and secondary 


class Customer {

    String name;

    Customer() {}

    Customer(String name)


class Customer() {

    lateinit var name: String

    constructor(name: String) : this()

#using instance of class


Customer customer = new Customer();
Customer customer1 = new Customer("Test");


val customer  = Customer()
val customer1 = Customer("Test")

#using inheritance 


public class Base {

    Base(int p)
public class Derived extends Base{

    Derived(int p) {


open class Base(p: Int)
class Derived(p: Int) : Base(p)

#using method overriding


public class Base {

   final void v() {}
   void nv() {}
public class Derived extends Base{

    void nv() {


open class Base {
    open fun v() {}
    fun nv() {}
class Derived() : Base() {
    override fun v() {}

#using static methods


class Customer {

   static String name = "Test";


class Customer {

    companion object {
         var name : String = "Test"


Thanks for reading 🙂

Spring 5 reactive web application using kotlin

Spring has introduced webFlux new reactive web framework to support reactive programming.

Reactive programming?

“Reactive programming is about processing an asynchronous stream of data items, where applications react to the data items as they occur. A stream of data is essentially a sequence of data items occurring over time. This model is more memory efficient because the data is processed as streams, as compared to iterating over the in-memory data” (define at Oracle docs) .

For example, in an imperative programming setting, a = b +c would mean that a is being assigned the result of  b + c in the instant the expression is evaluated , and letter the values of b and/or c can be changed with no effect on the value of a, However, in reactive programming, the valud of a is automatically updated whenever the values of b and/or  c changes, without the program having to re-execute the sentence a= b + c to determine the presently assigned value of a (click here for more detail) .

Prerequisites :

Spring boot
Spring 5 webFlux and Reactive basic(RxJava or Project Reactor)
Spring data

let generate spring boot template from Spring Initializr

Screen Shot 2017-11-26 at 11.13.34 AM

now import the generated project in your IDE and create Customer data class, check below example:-

Screen Shot 2017-11-26 at 11.35.48 AM

git link

@Document applied at the class level to indicate this class is a candidate for mapping to the database. You can specify the name of the collection where the database will be stored.

@Field applied at a variable level to define column name.

data class is specialized for hold data.

then created ‘Repository’ class look like below.

Screen Shot 2017-11-26 at 10.09.42 AM

git link

above class, I’ve extended ReactiveMongoReposiotry instead of MongoRepository because we are using Reactive features like Mono and Flux.

once ‘CustomerRepo’ repository classes created then create a handler for it, below code sample.

Screen Shot 2017-11-26 at 10.08.20 AM

git link

ServerRequest and ServerResponse introduce in spring 5, we can extract request param, path variable, header information and body details from ServerRequest.

Mono is a specialized Publisher that emits at most one item and then optionally terminates with an onComplete signal or an onError signal. click here for more detail.

Flux is a standard ‘Publisher’ representing an asynchronous sequence of 0 to N emitted items, optionally terminated by either a completion signal or an error. Thus, the possible values of a flux are a value, a completion signal, or an error. As in the Reactive Streams spec, these 3 types of signal translate to calls to a downstream object’s ‘onNext’, ‘onComplete’ or ‘onError’ methods. click here for more detail.

now we have handler and repository we need to expose endpoint, there is the magic of webFlux, you not need to create a separate class for it also get a ride from so much boilerplate, see below snippet.

Screen Shot 2017-11-26 at 10.07.39 AM

git link

Let me explain line by line,

@Configuration annotation indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.

@EnableReactiveMongoRepositories annotation is for Spring boot to enable reactive mongo repositories. if no base package is configured, in the case of spring boot application it is by default enable if you have include starter library.

@Bean is a method-level annotation and a direct analog of the XML element. The annotation supports most of the attributes offered by.

RouterFunction Central entry point to Spring’s functional web framework. Exposes routing functionality, such as to create a RouterFunction given a RequestPredicate and HandlerFunction, and to do further subroutine on an existing routing function.

HandlerFunction  Incoming HTTP requests are handled by a HandlerFunction, which is essentially a function that takes a ServerRequest and returns a Mono
let’s test whatever we have written, see below code snippet.

Screen Shot 2017-11-28 at 4.59.39 AM

git link

By default Spring webFulx include asynchronous natty server.

@RunWith(SpringRunner::class) Indicates that the class should use Spring’s JUnit facilities.

@SpringBootTest provides the following features over and above the regular Spring TestContext Framework,

  • Uses SpringBootContextLoader as the default ContextLoader when no specific @ContextConfiguration(loader=…) is defined.
  • Automatically searches for a @SpringBootConfiguration when nested @Configuration is not used, and no explicit classes are specified.
  • Allows custom Environment properties to be defined using the properties attribute.
  • Provides support for different webEnvironment modes, including the ability to start a fully running container listening on a defined or random port.
  • Registers a TestRestTemplate bean for use in web tests that are using a fully running container.

WebTestClient Non-blocking, reactive client for testing web servers. It uses the reactive WebClient internally to perform requests and provides a fluent API to verify responses.

WebTestClient can connect to any server over an HTTP connection. It can also bind directly to WebFlux applications using mock request and response objects, without the need for an HTTP server.


There are lots more features provided by Spring 5 and project reactor, I’ve introduced very basic sample on it. sample source available on my github .

Configure GitLab Runner with shell

Hi ,

I’ve found many examples where people configure with docker, in some cases if we need simple configuration for internal uses, we have also an alternative that can help to configure your GitLab CI runner easily.

In my case, i’m using Centos.

  1. added gitlab multi runner to yum repository

# curl -L | sudo bash

2.after added to repository install gitlab-multi runner
#sudo yum install gitlab-ci-multi-runner

once gitlab runner install, it will create “gitlab-runner” user in your machine

may find here “/home/gitlab-runner” , gitlab-runner user do not have permission you need to add it to user group or something else whatever you need.

you can also see multiple commands provided by gitlab runner

#gitlab-runner –help

now ,we need to configure it with our gitlab hosted repository

#sudo gitlab-ci-multi-runner register 

Please enter the gitlab-ci coordinator URL (e.g. )
Please enter the gitlab-ci token for this runner
Please enter the gitlab-ci description for this runner
INFO[0034] fcf5c619 Registering runner… succeeded
Please enter the executor: shell, docker, docker-ssh, ssh?
running already the config should be automatically reloaded!


after gitlab runner successfully configure you will see “admin area ->Runner” in gitlab

something similar to below images

Screen Shot 2016-10-08 at 5.29.43 PM.png

that is not completed yet you also need to configure Ci with include this file in your project root directory “”

added some configuration related to your project build and unit test running etc..

here is simple example i’ve added in “.gitlab-ci.yml” file

– cd spirng-mvc
– echo “making build”
– ./gradlew clean
– ./gradlew build

once configuration done, every commit we can run our build

Screen Shot 2016-10-08 at 5.55.33 PM.png

may I have skip few steps, let us know if needed will update.

Thank for reading 🙂

Strategy pattern in java

Hi Friends,

today i want to share strategy pattern, of course this is very well known and mostly used pattern. and their is lots of cases where we need to use strategic pattern.

#what is Strategy pattern?

The strategy pattern(also known as the policy pattern) is a software design pattern that enables an algorithm’s behavior to be selected at runtime. The strategy pattern. defines a family of algorithms, encapsulates each algorithm, and makes the algorithms interchangeable within that family. more

#When to use?

when we have multiple algorithm for a specific task and want to decides the actual implementation to be used at runtime


Suppose there is one software startup company and they have limited resource to done their work but all resource have multi-talent to do multiple roles,  like four resources (EmployeeA, EmployeeB, EmployeeC, EmployeeD) each one can able to done coding, testing,content writing etc. and any work can assign to anyone . its depend on availability.

Screen Shot 2015-10-22 at 3.10.43 AM

you can find example on Github link



Chat application over xmpp protocol

Hi folk,

Today I’m going to share simple chat application that is based on xmpp protocol.

i know that they have lost of question in your mind about xmpp , so simply i’m start with some definition or basic question

# what is xmpp ?

xmpp is the extensible messaging and presence protocol, a set of open technologies for instant messaging,presence,multi-party chat, voice and video calls, collaboration, lightweight middleware, content syndication,and generalized routing of xml data.

XMPP was originally developed in the Jabber open-source community to provide an open, decentralized alternative to the closed instant messaging services at that time. click here for more detail

# Why xmpp?

#Open standard – its gives you the choice and control about how you access your data and service

#multi platform support – you can create chat application for the multiple platform over the xmpp protocol

# xmpp implementation :

For the xmpp chat application we have to implement chat client and  configure server. firstly we are talking about chat client then we going to implement server configuration.


The following assumes that you have already basic knowledge in Android development with android studio

1.Android studio

2.Smack 4.1 library (smack 4.1 supporting android for previous version we need to implement asmack  library)

#Example :

step 1 > Create a project in android studio(File -> New Project(add Application name,project location) -> check phone and teblet and select minimum sdk -> select activity type -> define activity name ->finish) for more detail how to manage a project in android studio click here

add library detail in build.gradle file as below



step 2 > after adding library into project , now connect to openfire server and login as user



above this code example i have disable ssl and DIGEST-MD5 . According to your need you can enable it.

if you want to create user through your application then use AccountManager classto do it as for exp :

Account_manager step 3 > after successfully connected to chat server now create a chat with another user and receive there message


Above this code i’ve created doChat method where we need to pass userId(userId withwhome we want to chat) and implement ChatMessageListner to recive user message.

I hope a tutorial is helpful

Thanks for reading 🙂