SELECT vs FIND() [search records in Mongo way]

mongoselect.png

In the previous post we have seen some of the basic operations we perform on the mongo db from java. Today we will focus only on the SELECT operations.

In this post we will go through different searching operations such as , Greater than, less than, equals,  and some or the Logical operations such as And, Or, Not  and others such as  Starts with, Ends With, Contains,IN etc .

Before going into the program, lets setup a basic database and sample collections data.
Run the below script on your mongoDB, so that you will be ready with test data.

use mydb

db.user.save({"name":"jhon","email":"jhon@gmail.com","password":"jhon134","salary":2000})
db.user.save({"name":"casey","email":"casey@gmail.com","password":"casey","salary":1025})
db.user.save({"name":"candis","email":"candis@gmail.com","password":"candis","salary":100})
db.user.save({"name":"marcus","email":"marcus@gmail.com","password":"marcus","salary":250125})

The key point here is  to perform equal, less than, greater than, and Logical operations, the mongo java driver 3.2 provided very use full class com.mongodb.client.model.Filters.
It is a final class provides many static methods, to perform the search operations.

To perform string search operations such as Starts with, ends with, contains we need to opt for regular expressions.The important point here is , in relations databases we use ‘%’ the equivalent value for that in Mongo db is ‘.*’

Having the database ready, now lets jump into the code, all the respective operations description is written in comments.

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import static com.mongodb.client.model.Filters.regex;
import java.util.ArrayList;
import java.util.regex.Pattern;
import org.bson.Document;

public class SomeMoreSelectOperations {

    public static void main(String[] args) {

        // connect to mongodb
        MongoClient mongoClient = new MongoClient("localhost");
        MongoDatabase database = mongoClient.getDatabase("mydb");

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

        // equals
        collection.find(Filters.eq("name", "jhon"));

        // less than
        collection.find(Filters.lt("salary", 200));

        // greater than
        collection.find(Filters.gt("salary", 200));

        //Logical operations

        // where salary less than 200 and greater than 100
        collection.find(Filters.and((Filters.lt("salary", 200)), (Filters.gt("salary", 1000))));

        // where salary less than 200 or greater than 100
        collection.find(Filters.or((Filters.lt("salary", 200)), (Filters.gt("salary", 1000))));

        // where salary neither 200 nor 1000
        collection.find(Filters.nor((Filters.lt("salary", 200)), (Filters.gt("salary", 1000))));

        // not equals
        collection.find(Filters.not(Filters.eq("salary", 200)));

        //IN operation
        ArrayList values = new ArrayList();
        values.add(200);
        values.add(100);
        values.add(3000);
        collection.find(Filters.in("salary", values));

        // contains
        Pattern pattern = Pattern.compile(".*" + Pattern.quote("contain string") + ".*", Pattern.CASE_INSENSITIVE);
        MongoCursor<Document> cursor = collection.find(regex("columnName", pattern)).iterator();

       // For startswith
        Pattern pattern1 = Pattern.compile("^" + Pattern.quote("begin string"), Pattern.CASE_INSENSITIVE);
        MongoCursor<Document> cursor1 = collection.find(regex("columnName", pattern1)).iterator();

       // For endswith
        Pattern pattern2 = Pattern.compile(Pattern.quote("end string") + "$", Pattern.CASE_INSENSITIVE);
        MongoCursor<Document> cursor2 = collection.find(regex("columnName", pattern)).iterator();

        // iterate throght the cursor
        while (cursor2.hasNext()) {
            Document doc = cursor2.next();
            System.out.println(doc);
        }

    }

References:
http://stackoverflow.com/questions/37120845/mongodb-find-contains-startswith-endswith-and-exact-string-with-java-driver

Posted in mongodb | Tagged , , | 1 Comment

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/

Posted in mongodb | Tagged , , , | 1 Comment

5 ways to connect to MongoDB

mongojava

I have been working on Mongo java 2.x driver , Recently we planned to update our Java driver version to 3.x.  Then i got realized that a lot has been changed.
Now lets start working on Mongo-Java-Driver 3.2 version.

Depenedency:

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

Example Program:

Lets look at the different ways to connect to the mongoDB

public class ConnectToMongoDb {
    public static void main(String[] args) {

        // 1. directly connect to single local mongo server
        MongoClient mongoClient1 =  new MongoClient();

        //2. or
        MongoClient mongoClient2 =  new MongoClient("localhost");

        //3. connect to the local mongo server with specific port
        MongoClient mongoClient3 =  new MongoClient("localhost",27017);

        //4 connect to the mongo servers with auto discovery features
        MongoClient mongoClient4 =  new MongoClient(
                Arrays.asList(new ServerAddress("localhost", 27017),
                              new ServerAddress("localhost", 27018),
                              new ServerAddress("localhost", 27019)));

        //5 connect to mongo server using connection string
        MongoClientURI mongoClientURI =  new MongoClientURI("mongo://username:passowrd@localhost:27018/dbname");
        MongoClient mongoClient5= new MongoClient(mongoClientURI);

        MongoDatabase database = mongoClient1.getDatabase("databaseName");
    }
}

References:
http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/installation-guide/

Posted in mongodb | Tagged , , , , | 1 Comment

Json to CSV using ng-csv

ng-csv.png

ng-csv is the simple directive that converts arrays and objects to CSV files.

Steps:

1. Add ng-csv.min.js  and angular-sanitize.min.js
    cdn for these are :


2. add 'ngSanitize', 'ngCsv' dependecies to your module
3. use ng-csv directive in html

Lets see a sample application

<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <!--angular js-->
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>

        <!--ngcsv CDN-->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/ng-csv/0.3.6/ng-csv.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.5.8/angular-sanitize.js"></script>

        <script>
            angular.module('app', ['ngSanitize', 'ngCsv']).controller('downloader', function($scope) {
                // json data to be exported
                $scope.data = [
                    {
                        "id": "1",
                        "name": "avis"
                    },
                    {
                        "id": "2",
                        "name": "tasis"
                    },
                    {
                        "id": "3",
                        "name": "ticus"

                    }
                ]
            });
        </script>
    </head>
    <body ng-app="app" ng-controller="downloader">
<table border="1px">
<th>Id</th>
<th>Name</th>
<tr ng-repeat="user in data">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
</tr>
</table>
<h3> Hello , click the below button to export your data to CSV</h1>
<button class="btn  btn-xs btn-white" ng-csv="data" filename="mycsvfile.csv">Download Report</button>
</body>
</html>

References:

https://github.com/asafdav/ng-csv
http://ngmodules.org/modules/ng-csv

Posted in angularjs | Tagged , , , , | Leave a comment

Export JSON TO CSV Using AlaSQL.js

jsontocsv

AlaSQL is a client side in memory SQL database. It is very light weight and fast.It is fully functional and work in all modern browsers.

Below program show to we can export json data to CSV format, and download it.

STEPS:

1. ADD alasql libray  (you can dowload js file or use cdn ) 
     https://cdn.jsdelivr.net/alasql/0.3/alasql.min.js
2. WRITE QUERY FROM YOUR JSON.
      EX: (SELECT * INTO FILENAME.XLSX FROM $scope.data )
3. RUN THE FILE
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <!--angular js-->
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>

        <!--alasql library-->
        <script src="https://cdn.jsdelivr.net/alasql/0.3/alasql.min.js"></script>

        <script>
            angular.module('app', []).controller('downloader', function($scope) {
                // json data to be exported
                $scope.data = [
                    {
                        id: 1,
                        name: "avis",

                    },
                    {
                        id: 2,
                        name: "tasis"
                    },
                    {
                        id: 3,
                        name: "ticus"
                    }
                ]

                $scope.downloadReports = function() {   // we can download our json data in many formats. ex: csv, excel
                   // var filename = "someFileName.xlsx"
                    var filename = "someFileName.csv"
                    //alasql('SELECT id as ID,name as Name INTO XLSX("' + filename + '",{headers:true}) FROM ?', [$scope.OrganizationUsersList]);
                    alasql('SELECT id as ID,name as Name INTO CSV("' + filename + '",{headers:true}) FROM ?', [$scope.data]);

                }

            });
        </script>
    </head>
    <body ng-app="app" ng-controller="downloader">
<table border="1px">
<th>Id</th>
<th>Name</th>
<tr ng-repeat="user in data">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
</tr>
</table>
<h3> Hello , click the below button to export your data to CSV</h1>
<button class="btn  btn-xs btn-white" ng-click="downloadReports()">Download Report</button>
    </body>
</html>
References:
http://alasql.org/
jsfiddle
Posted in angularjs | Tagged , , , , | Leave a comment

Check Prime Or not

public class CheckPrimeOrNot {
	public static void main(String[] args) {
		int number = 5;
		System.out.println(isPrimeOrNot(number));
	}

	private static String isPrimeOrNot(int number) {

		if (number < 0)
			return "invalid number";
		if (number == 0 || number == 1)
			return "not prime";
		if (number == 2 && number == 3)
			return "prime number";

		if (number % 2 == 0) {
			return "not prime";
        }

		int sqrt = (int) Math.sqrt(number);

		for (int i = 3; i < sqrt; i += 2) {
			if (number % i == 0) {
				return "not a prime number";
			}
		}

		return "prime";
	}
}
Posted in Programing questions | Tagged , , | Leave a comment

Find the min and max in an Array

import java.util.Arrays;

/**
 * Java program to find maximum and minimum numbers in given array
 *
 *
 */
public class MaximumMinimumArray {

	public static void main(String[] args) {
		int numbers[] = {1,2,3,4,5,6,7};
		findMaxAndMin(numbers);
	}

	private static void findMaxAndMin(int[] numbers) {
		int smallest = numbers[0];
		int largest = numbers[0];

		for (int i : numbers) {
			if(i > largest){
				largest = i;
			}else if(i <smallest){
				smallest = i;
			}
		}

		System.out.println("Given integer array :"+Arrays.toString(numbers));
		System.out.println("larget number : "+ largest);
		System.out.println("smallest number : "+ smallest);

	}
}
Posted in Programing questions, Uncategorized | Tagged , , | Leave a comment