Thursday, 13 April 2017

No-Sql DataBase

NoSQL Database is used to refer a non-SQL or non-relational database.
Relational database could not handle big data, due to this problem there was a need of database which can handle every types of problems then NoSQL database was developed.


Advantage of NoSQL Database-
1)     It supports query language.
2)     It provides fast performance.
3)     It provides horizontal scalability.


Mongo DB –
1)     MongoDB is schema less. It is a document database in which one collection holds different documents.
2)     There may be difference between number of fields, content and size of the document from one to other.
3)     Structure of a single object is clear in MongoDB.
4)     There are no complex joins in MongoDB.
5)     MongoDB provides the facility of deep query because it supports a powerful dynamic query on documents.
6)     It is very easy to scale.
7)     It uses internal memory for storing working sets and this is the reason of its fast access.


Mongo DB setup–

Download mongoDb server - download-center
Follow step mention in below link to install the setup.
For GUI download mongo compass


Mongo DB script –

Navigate to mongoDb installation directory C:\Program Files\MongoDB\Server\<mongo-version>\bin, open command prompt and execute mongo.exe, now you can run mongo commands, refer below for the list of mongocommands-
While executing mongo.exe we can also specify the path of database folder as below
"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --dbpath="c:\data\db"
Although default directory is <absolute installation path>\data\db
1-     Show database – show dbs, show databases
2-     Use and create database – use <databaseName>
3-     Drop database- use <databaseName> ; db.dropDatabase()
4-     Get all collection – show collections
5-     Create collection – db.createCollection(<collectionName>)
6-     Drop collection- db.<collectionName>.drop()
7-     Select query- db.<collectionName>.find()
8-     Select query with formatted response – db.<collectionName>.find().pretty()
9-     Select query with condition –db.<collectionName>.find({<queryCondition>}).pretty()
10- Select query with multiple conditions
Db.<collectionName>.find({<col1>:<value1>, <col2>:<value2>})
11- Insert document- db.<collectionName>.insert({<document>});
12- Update document –
db<collectionName>.update({<condition>} ,  "$set": {<col>:<newValue>}})
db.<collectionName>.update({<columnePath>:<oldvalue>},{"$set": {{<colpatch>:<newValue>})
13-  Remove document –
db.<collectionName>.remove({<queryCondition>})
14-  Remove all document –
db.<collectionName>.remove({})
15-  Get executionStats of query-
db.<collectionName>.find().explain(“executionStats”)
db.<sollectionName>.explain(“executionStats”).update({<document>})
db.collecion.explain() returns information on the query plan for following operation:
aggregate(); count(); distinct(); find(); group(); remove(); and update().


Basic mongo query and CRUD operation are already mention above in this blog
Here we are explaining some other feature to make the query robust.

Create Index
We can create index to make query faster.
To create index we use below query-
> db.student_details.ensureIndex({"firstName":1})
In java code use @Indexed on the field for simple index and use @CompundIndex for creating index on multiple fields.
@Document(collection = "student_details")
@CompoundIndexes({
    @CompoundIndex(name = "id_firstName", def = "{'id' : 1, 'firstName': 1}")
})
public class Student {
////**//
}
Here name is the name of index and inside def mention the fileld name for this index
Refer below for more details- https://docs.mongodb.com/manual/indexes/

Aggregation-
Use aggregate function for the grouping of multiple documents together and perform different operations, sum, min, max, avg etc.
> db.student_details.aggregate([{$group : {_id : "$firstName", usercount : {$sum : 1}}}])
{ "_id" : "Atul", "usercount" : 3 }
{ "_id" : "Manoj", "usercount" : 3 }


Create DB and Collection from Java code and perform crud operation.

Refer below code – create a spring boot application.
Build.gradle-
plugins {
     id 'org.springframework.boot' version '2.1.7.RELEASE'
     id 'io.spring.dependency-management' version '1.0.8.RELEASE'
     id 'java'
}

group = 'com.mk'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
     mavenCentral()
}

dependencies {
     compile("org.springframework.boot:spring-boot-starter-data-mongodb")
     implementation 'org.springframework.boot:spring-boot-starter'
     testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
Create a Student.java model class and specify the collection details as below-
package com.mk.database.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "student_details")
public class Student {
     @Id
     public String id;
     public String firstName;
     public String lastName;

     public Student() {
     }
     public Student(String firstName, String lastName) {
           this.firstName = firstName;
           this.lastName = lastName;
     }
     public String toString() {
           return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
     }
}
Create StudentRepository.java
package com.mk.database.dao;

import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.mk.database.model.Student;

public interface StudentRepository extends MongoRepository<Student, String> {
     public Student findByFirstName(String firstName);
     public List<Student> findByLastName(String lastName);
}
Now create the configuration for database details –
package com.mk.database;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mk.database.dao.StudentRepository;
import com.mk.database.model.Student;
import com.mongodb.MongoClient;

@SpringBootApplication
public class DatabaseApplication implements CommandLineRunner {

     @Autowired
     private StudentRepository repository;

     public static void main(String[] args) {
           SpringApplication.run(DatabaseApplication.class, args);
     }
     public void run(String... args) throws Exception {
           repository.save(new Student("Manoj", "Kumar"));
           repository.save(new Student("Atul", "Kumar"));
           for (Student student : repository.findAll()) {
                System.out.println(student);
           }
     }
     @Bean
     public MongoTemplate mongoTemplate() {
           return new MongoTemplate(new MongoClient("localhost:27017"), "student_db");
     }
}

Create mongo template for secure database use below code.
@Bean
public MongoTemplate mongoTemplate() {
     List<ServerAddress> serverAddresses = new ArrayList<>();
     serverAddresses.add(new ServerAddress("mongodb://127.0.0.1:27017"));
     final MongoCredential credential = MongoCredential.createCredential("<username>", "<databaseName>",
                "<password>".toCharArray());
    
     return new MongoTemplate(new MongoClient(serverAddresses, credential, MongoClientOptions.builder()
                .writeConcern(WriteConcern.MAJORITY)
                .readPreference(ReadPreference.primaryPreferred()).build()), "");
     // return new MongoTemplate(new MongoClient("localhost:27017"), "student_db");
}



2 comments: