How to Insert Document in mongodb collection ?

The tutorial provides the steps to insert document using MongoDB. A document is inserted in mongodb using insert() , insertOne() , insertMany() methods which we will discuss in detail with examples.

Insert Document in MongoDB

MongoDB stores the data into documents. The below points can be considered for the Insert Document in MongoDB

  • MongoDB allows to insert a single document in a collection
  • MongoDB allows to insert multiple documents in a collection
  • If the collection does not exist, MongoDB will automatically creates the collection
  • Each document in a collection requires a unique field (_id) which represents as the Primary Key for the document. MongoDB generates the ObjectId automatically if the _Id is not provided during the Insert Document
  • MongoDB ensures atomicity for the write operations

What is objectId in MongoDB ?

An ObjectId is :

  • An unique key or id
  • it is faster to generate
  • it has 12 bytes length ( 4 byte – timestamp for objectId creation, 5 byte – random value , 3 byte – incrementing counter)
  • ObjectId creation can be accessed by ObjectId.getTimestamp() method

The Insert Document Methods in MongoDB

Option 1: Insert Document 

Syntax –  db.collectionname.insert(document)

This command is the basic command to insert document where collectionname is the name of the collection, insert is the CRUD Operation for inserting single or multiple document. The below given is the sample for inserting document

> db.oracelappsUsers.insert({
… name: "Mohit Sharma",
… userType: "Admin",
… description: "MongoDB insert document sample",
… createdBy: "oracelappshelp.com"
… })
WriteResult({ "nInserted" : 1 })
>

The inserted record can be validated by the below find command. Although we had not provided the _Id  ( unique value) for the inserted document, but MongoDB automatically creates the _id as given below.

>db.oracelappsUsers.find( { name: "Mohit Sharma" } )
{ "_id" : ObjectId("5f12fd48d4a587e31cddd7e5"), "name" : "Mohit Sharma", "userType" : "Admin", "description" : "MongoDB insert document sample", "createdBy" : "oracelappshelp.com" }

Option 2: Insert Single Document

Syntax – db.collection.insertOne()

This command allows to insert the single document in the collection. The below example illustrates the same.

> try {
… db.oracleappshelpproducts.insertOne( { item: "MongoDBMockTest", qty: 1 } );
… } catch (e) {
… print (e);
… };

MongoDB executes the insertOne() for the single document and returns the acknowledgment with the generated objectId (_Id) value.

{
     "acknowledged" : true,
     "insertedId" : ObjectId("5f1302733a96070d59afd2bf")
}
>

Another example for insertOne() where _id is being provided. MongoDB considers the same _id and returns it back with the acknowledgement for the inserted document.

>try {
… db.oracleappshelpproducts.insertOne( { _id: 21, item: "MongoDBTutorialPDF", qty: 1 } );
… } catch (e) {
… print (e);
… };
{ "acknowledged" : true, "insertedId" : 21 }

Option 2: Insert Multiple Document

Syntax – db.collection.insertMany()

This command allows to insert the multiple document in the collection. The below example illustrates the same.

> try {
… db.oracleappshelpproducts.insertMany(
… [
… { _id: 22, item: "SQLServerTutorialPDF", qty: 1 } ,
… { _id: 23, item: "CouchDBTutorialPDF", qty: 1 },
… { _id: 24, item: "CassandraTutorialPDF", qty: 1 }
… ]);
… } catch (e) {
… print (e);
… };

The below given is the return output by MongoDB for the Bulk Insertion of multiple documents.

{ "acknowledged" : true, "insertedIds" : [ 22, 23, 24 ] }
>

Insert Document Error for Duplicate Key in collection

In case the _Id is repeated for the inserted document , MongoDB returns the Duplicate Key error in the collection as given below.

> try {
db.oracleappshelpproducts.insertMany(
[
{ _id: 21, item: "SQLServerTutorialPDF", qty: 1 } ,
{ _id: 21, item: "CouchDBTutorialPDF", qty: 1 },
{ _id: 21, item: "CassandraTutorialPDF", qty: 1 }
]);
} catch (e) {
print (e);
};

>BulkWriteError({
"writeErrors" : [
{
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test.oracleappshelpproducts index: id dup key: { _id: 21.0 }",
"op" : {
"_id" : 21,
"item" : "SQLServerTutorialPDF",
"qty" : 1
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
>

How to Create & Drop collections in MongoDB

The tutorial provides the steps to create a collection and drop a collection using MongoDB. A collection is created in mongodb using createCollection()

Document: A document is single unit or data record similar to a row in RDBMS for storing information. A document is a JOSN object storing data in the form of key-value pairs.

Collection:  A collection is a group of documents for storing data similar to RDBMS tables. MongoDB contains multiple collections in the database similar to RDBMS which contains multiple tables in the database

Create Collection in MongoDB

The MongoDB provides the method – db.createCollection(name, options) to create a collection.

Create Collection Syntax:

db.createCollection(name, options)

Where

name is the collection name

options is the document to specify collection configuration

Argument Argument Type Argument Description
Name String Name of the Collection
Options Document Optional. Configuration details like Memory Size, Indexing
capped Boolean

Optional.  Enables the Capped Collection which are fixed size collections.  When reached max size (in bytes) , capped collection overwrites the old entries

autoIndexId Boolean

Optional.

When enabled , creates index on _id field.

size Number

Optional.

Used in Capped Collection . When enabled, specify max size in bytes

max Number

Optional.

When Enabled, allows to specify max documents in the Capped Collection.

Lets execute a simple collection method call for creating the collection in MongoDB

> use oracleappshelpDB
switched to db oracleappshelpDB
> db.createCollection("oracleappsHelpBCollection")
{ "ok" : 1 }

The OK depicts that the collection – “oracleappsHelpBCollection” is created. We can verify by executing the show collections 

> show collections
oracleappsHelpBCollection
>

Let’s execute create collection method with the Optional arguments

> db.createCollection("oracleappscol", { capped : true, size : 10240, max : 1000 } )
{
"ok" : 0,
"errmsg" : "16: Resource device",
"code" : 8,
"codeName" : "UnknownError"
}
>

Note that we do not need to create collections in MongoDB as it automatically creates the collection when an document is inserted.

The below MongoDB Insert Document command shows the created collections.

> db.oracleappshelpDB.insert({"studentName" : "Mohit Sharma"})
WriteResult({ "nInserted" : 1 })
> show collections
oracleappsHelpBCollection
oracleappshelpDB
>

Drop collection in MongoDB

The MongoDB provides the method – db.collection.drop() to drop a collection.

The MongoDB provides the method – db.collection.drop(name, options) for dropping the collections.

Drop Collection Syntax:

db.Collection.drop()

Where

Collection is the name of the collection.

The below command show collections list down the available collections for the Database – oracleappshelpDB

> show collections
oracleappsHelpBCollection
oracleappshelpDB
>

Now , drop the collection – oracleappshelpDB from the database by executing the below command

> db.oracleappshelpDB.drop()
true
>

java array program to identify sub arrays with element sum equal to Zero

Core Java Array interview questions on the identification of multiple sub arrays within in the Array Input whose array elements sum is Zero.

Program Logic:

– Java Array provided with the list of array elements.
* Traverse the elements to identify if the value of that element is zero.
* Traverse the elements to identify if the value of multiple array elements sums up to Zero
* Print each such occurrence as an sub-array

package core.java.oracleappshelp.array;
public class identifySubArrayInArrayWithSumZero {
	// Function to print all sub-arrays with 0 sum present
		// in the given array
		public static void identifySubArrayToDisplay(int[] ArrayWithAllElements)
		{
			// Traverse for the sub- array through the outerLoop
			for (int outerLoop = 0; outerLoop < ArrayWithAllElements.length; outerLoop++)
			{
				int sum = 0;
				// Traverse for the sub- array through the innerLoop
				for (int innerLoop = outerLoop; innerLoop < ArrayWithAllElements.length; innerLoop++)
				{
					// adding value for innerLoop and outerLoop to get total sum value.
					sum += ArrayWithAllElements[innerLoop];
					// validate if the array index for innerLoop and OuterLoop sums up to 0
					if (sum == 0) {
						System.out.println("Subarray [" + outerLoop + ".." + innerLoop + "]");
					}
				}
			}
		}
			public static void main (String[] args)
		{
			int[] A = { -2, 2, 1, 5, -6,  3, 1, -4,  };
			identifySubArrayToDisplay(A);
		}
}

java array program to sort list in binary of 0s and 1s

The  below java program executes the java method – sortArrayElementsInBinaryFormat( ) to sort the received list into the Binary format of 0s and 1s in sequence.

Program Logic:

1. Pass the Array Element List to the method – sortArrayElementsInBinaryFormat( )

2. Traverse and identify the elements with 0 value

3. Move the elements with 0 value forward and elements with value 1 thereafter

4. Print the sorted binary array

Array Input :  { 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0 }

Array Output: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

/*
 * Java Array Program to sort the received Array Binary Input of 0 and 1
 * identify the elements with 0 value
 * Move the elements with 0 value forward in the Array 
 * elements with 1 value to be placed after all 0s 
 * Input : { 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0 }
 * Output: {0,0,0,0,0,1,1,1,1,1,1}
 */
package core.java.oracleappshelp.array;
import java.util.Arrays;
public class GenerateBinaryArray {
/*  Method - sortArrayElementsInBinaryFormat
 *  Java Method to sort the received list into the Binary format of 0 and 1 in sequence.
 */
		public static void sortArrayElementsInBinaryFormat(int[] arrayElements)
		{
			// identify the elements with 0 value
			int elementWithZeroValue = 0;
			for (int elementValue : arrayElements) {
				if (elementValue == 0) {
					elementWithZeroValue++;
				}
			}
			// move the elements with 0 value forward and elements with value 1 thereafter
			int elementLoop = 0;
			while (elementWithZeroValue-- != 0) {
				arrayElements[elementLoop++] = 0;
			}
			// fill all remaining elements by 1
			while (elementLoop < arrayElements.length) {
				arrayElements[elementLoop++] = 1;
			}
		}
		// Sort binary array in linear time
		public static void main (String[] args)
		{
			int[] arrayElementList = { 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0 };
			sortArrayElementsInBinaryFormat(arrayElementList);
			// print the sorted binary array
			System.out.println(Arrays.toString(arrayElementList));
		}
}
Java Array Program Output: 
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

Main differences between Array and ArrayList in java

How is an array different from ArrayList ? What are the major differences between Array and ArrayList ? Why difference between Array and ArrayList is the most commonly asked Java Interview Question . Below given are the points for Array vs ArrayList which describes it.

S. No     Array     ArrayList
1 Array is fixed length , thus static in nature ArrayList  is dynamic in nature
2 Array does not extend any class or implement interface ArrayList implements the List Interface and internally backed by Array
3 Array does not support Generics and throws ArrayStoreException ArrayList supports Generics and ensures type-safety.
4

Array provides length() method to calculate

the Array Length

Example:

int studentObject[] = new Integer[3];int
int studentObjectLength= studentObject.length ;

ArrayList provides size() method to calculate the ArrayList size

Example:
ArrayList studentObject = new ArrayList();
studentObject.add(101);
studentObject.add(102);
studentObject.size();

5 Arrays allows to store primitive types and objects ArrayList allows to store objects only
6

Array uses assignment operator to store element into array

Example:

int[] studentId = { 101, 102,103,104,105 };

Object[] studentId = new Object[10];

ArrayList uses add() method to store element in ArrayList

Example:

ArrayList<Integer> studentIdList = new ArrayList<Integer>();
studentIdList.add(100);

7

Arrays are faster when frequent access is required.

Array operations execution time

Arrays Lookup –  O(1)

Arrays Append ( last element) – O(1)

Array Insertion – O(n)

Array Deletion – O(n)

ArrayList is faster when frequent insert and deletion is required.  Overall ArrayList takes  more time as it uses List interface as part of Collection Framework and each node in the List has its own memory when compared to Arrays.
8

Array is traversed using for loop

ArrayList is traversed using Iterator

 

Top 30 Java Array Interview Questions & Answers

Java array is the most important and commonly asked topic in programming interview questions. The Tutorial shares the top 30 java array interview questions and answers for IT exam or interview preparation. Java Array is one of the used data structure in java programming and thus important for beginners and experienced programmers to possess clarity on java array implementation.

1. What is an Array in java ?

  • Java Array is the data structure with the collection of elements to organize and store the objects sequentially.
  • Array in java uses index for each position. Array Index starts from 0 position.
  • Array stores the collection of elements with the similar data types.
  • Array are fixed in length and thus not expandable in size.
  • Array objects in java are stored in the heap memory and not on the stack.
  • Arrays can be categorized as 1-dimensional array, 2 -dimensional array, N-dimensional array.
  • Arrays in java are implemented in other data structures like List, Heap, Hash Tables, Queues, Strings.
  • The simplest example of Array data structure could be a linear array (also called 1-dimensional array)

2. What are the advantages and disadvantages of array in java?

Advantages:

  • Arrays in java provides fast lookup (retrieval / traversal) of elements using index.
  • Array retrieval takes o(1) times irrespective of the array length
  • Appending array with new element at the end of the array works faster , takes O(1) time.

Disadvantages:

  • Arrays in java are of fixed length and thus cannot be expandable at run time.
  • Collection of elements in array should be of same data type.
  • Array insertion and Array deletion take O(n) time and thus makes the operation costlier with respect to execution time.

Below given are the Array operations and their execution time.

Array OperationsArray Execution Time
Array SpaceO(n)
Array Lookup / RetrievalO(1)
Array Append (last element) O(1)
Array Insertion O(n)
Array Deletion O(n)

3. How the array is stored ?

Array is an object in the java and it is being stored in the heap memory in the JVM

4. Can the array be declared without size?

No. Array is fixed length in java and need to be initialized with size.

5. Does Array allows adding string value into Integer Array ?

We know that Arrays in java is the collection of elements with the same data type. Thus , storing string value in Integer Array gives the compile time error.

package core.java.oracleappshelp.array;
public class AssingStringToIntArray {
	 public static void main(String args[]) {
			int[] assingIntValue = new int[5];
			assingIntValue[0] = "Mohit";   //compile time error
	 }
}

6. Explain ArrayStoreException and hierarchy in Java Array ?

The ArrayStoreException exception occurs when the object is stored with a different data type which is not same as per the defined array object. Let’s consider another example. Create an Array of object assigned with String [ ] . Add the integer value. In this case, although compiler doesn’t give compile time error but it does generates ArrayStoreException  at the run-time.

package core.java.oracleappshelp.array;
public class ArrayStoreExceptionExample {
	public static void main(String[] args) {
        Object[] students = new String[10]; 
        students[0] ="Rohit";
        students[1] ="Mohit";
     // assignment of integer generates ArrayStoreException at run time.
        students[2] = new Integer(0);         
	}
}
Program Output:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
	at core.java.oracleappshelp.array.ArrayStoreExceptionExample.main(ArrayStoreExceptionExample.java:8)

ArrayStoreException Class Hierarchy:

java.lang.Object
↳ java.lang.Throwable
    ↳ java.lang.Exception
        ↳ java.lang.RuntimeException
            ↳ java.lang.ArrayStoreException 

Constructors of ArrayStoreException:

  • ArrayStoreException(): Constructs an ArrayStoreException instance with no detail message.
  • ArrayStoreException(String storeExcMessage): Constructs an ArrayStoreException instance with the specified message

7. What are the common errors / exceptions in Arrays ?

  • NullPointerException : when value accessed is retrieved as NULL at run-time.
  • NegativeArraySizeException when array is identified with a negative size
  • ArrayIndexOutOfBoundsException : When array is accessed or modified with a invalid index or index value is idnetiifed more than the array size.
  • ClassCastException :
package core.java.oracleappshelp.array;
public class ArrayClassCastExceptionExample {
		public static void main(String[] args) {
			Object storeIntValues = new Integer(10);  
			System.out.println((String)storeIntValues);            
		}
	}
Program Output: 
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
	at core.java.oracleappshelp.array.ArrayClassCastExceptionExample.main(ArrayClassCastExceptionExample.java:6)

ArrayStoreException: Refer the above question explained with the example.

8. What is the default array value for different data types ?

Java Data TypeDefault Array Value
byte, short,int,long0
float, double0.0
boolean false
Objectnull

9. Is Generics use supported in array ?

No

10. Define anonymous array in java ?

The Array which does not have a name or reference is termed as anonymous array in java.

new String[]{“Open”, “Close”, “Save”};

new int[] {100,200,300,400,500};

11. What are jagged arrays in java ?

Arrays containing arrays with different size are termed as jagged arrays.

Example: Multi-dimensional arrays included Jagged arrays.

12. Can the array with higher size be assigned to an array with less size ?

Yes, arrays support this feature. If an array1 has size of 10 elements and array2 has size of 5 elements, then array1 can be assigned to array2 even though it has less element size as array validation checks for the array to be of same data type and does not validate on the array size during compilation.

import java.util.*;
public class CopyLargeArrayToSmallArraySize{
	public static void main(String args[]) {
		int[]  arrayWithLessSize = new int[20];
		int[]  arrayWithLargeSize = new int[40];
		arrayWithLessSize = arrayWithLargeSize;
		System.out.println(arrayWithLessSize.length);
    }
}

13. Write a java program to sort an array and print in java ?

The below java program uses Arrays.sort( ) method to sort the numbers in array

package core.java.oracleappshelp.array;
import java.util.Arrays;
public class arraySortingInJava {
	public static void main(String[] args) {
	    int[]  numberList = { 700, 100,500,900,50 };
	    Arrays.sort(numberList);
	    for (int traverseList : numberList)
	        System.out.print(traverseList +" ");
	}
}
Array Program Output:
50 100 500 700 900 

14. what are the possible ways to copy array content from one array to another ?

The below given methodologies can be applied in java for copy array content

  • Using for loop to traverse and copy the content
  • Using clone( ) method
  • Using Arrays.copyOf( ) method
  • Using System.arraycopy ( ) method

15. Describe the differences between Array and ArrayList ?

http://oracleappshelp.com/main-differences-between-array-and-arraylist-in-java/

16. What will be the ouput for an Array which is not initialized ?

The Array will be assigned with the Default Value based on the Array Data Type

17. Write a java program to identify duplicate array elements in java ?

package core.java.oracleappshelp.array;
public class IdenitfyDuplicateArrayElements {
/* Method Name - getDuplciateArrayElements 
 * Java method to identify the duplicate array elements from the received any input.
 */
public static void getDuplciateArrayElements(String[] studentNames) {
	    for(int outerLoop=0; outerLoop < studentNames.length-1; outerLoop++){
	        for(int innerLoop=outerLoop+1; innerLoop < studentNames.length; innerLoop++) {
	            
	            if(studentNames[outerLoop].equals(studentNames[innerLoop]) && outerLoop!=innerLoop ) {
	                System.out.println("Idneitifed duplicate array element  is : "+ studentNames[innerLoop]);
	            }
	        }
	    }
		
	}
	 public static void main(String args[]) {
		    String[]  studentNames = {"Roit", "Mohit", "Vinay", "Mohit", "Akshay" };
		    getDuplciateArrayElements(studentNames);
		  }
}

18. Is an array thread-safe in java ?

  • Array operation is java have their complexity.
  • Array Retrieval is thread-safe.
  • Array insertion, updation and deletion are not thread-safe.

19. Can array be made volatile ?

Only variable representing an array can be made volatile

20. Write a java program to check if the given two arrays are equal or not ?

The below given program uses Arrays.equal( ) method to validate if the comparison of two arrays is equal or not.

package core.java.oracleappshelp.array;
import java.util.Arrays;
public class ArraysComparison {
	public static void main(String[] args) {
		int[]  arrayObject_1 = { 700, 100,500,900,50 };
	    int[]  arrayObject_2 = { 700, 100,500,900,50 };
	    int[]  arrayObject_3 = { 100, 200,500,900,50 };
	    System.out.println(" Is Array Object 1 Equals to Array Object 3" + Arrays.equals(arrayObject_1 , arrayObject_2));
	    System.out.println(" Is Array Object 1 Equals to Array Object 3" + Arrays.equals(arrayObject_1 , arrayObject_3));
	    System.out.println(" Is Array Object 2 Equals to Array Object 3" + Arrays.equals(arrayObject_2 , arrayObject_3));
	    }
	}
    
Array Program Output: 
 Is Array Object 1 Equals to Array Object 3 true
 Is Array Object 1 Equals to Array Object 3 false
 Is Array Object 2 Equals to Array Object 3 false

21. How many ways multi dimesional arrays can be created in java ?

Multi Dimesional arrays in java could be 2D, 3D and 4D . Below given are the few examples of creating multi dimesional arrays in different ways

/* 2 Dimesional Arrays */

int[][] twoDimesionalArray1;
int twoDimesionalArray2[][];
int[] twoDimesionalArray3[];

/* 3 Dimensional Arrays */

int[][][] threeDimesionalArray1;
int threeDimesionalArray2[][][];
int[] threeDimesionalArray3[][]; 
int[][] threeDimesionalArray4[];

/*4 Dimesional Arrays */

int[][][][] fourDimesionalArray1;
int fourDimesionalArray2[][][][];
int[] fourDimesionalArray3[][][];
int[][] fourDimesionalArray4[][];
int[][][] fourDimesionalArray5[];

22. How to convert an array to arrayList in java ?

The below apprach can be used for converting an array to arrayList in java

  • Using Arrays.asList() method
   String studentNames[]={"Mohit", "Rohit", "Snehashish", "Akshay"};
   /* Using Arrays.asList() method to convert array to ArrayList */
   ArrayList<String> studentList= new ArrayList<String>(Arrays.asList(studentNames));
  • Using Collections.addAll() method
String studentNames[]={"Mohit", "Rohit", "Snehashish", "Akshay"};
/* Create ArrayList studentList*/
ArrayList studentList= new ArrayList();
/* Using Collections.addAll() method to convert array to ArrayList */    
 Collections.addAll(studentList, studentNames);

23. How to find the Second Largest Number in the Array in java ?

The below steps can be performed to identify the second largest array element in java

  • Intitialize the array with the array elements
  • Sort the Array by using Arrays.sort() method
  • The last Number is the Array is the largest number after sorting
  • Traverse the array elements from 0 to n-2
  • compare the array element with the last element in array
package core.java.oracleappshelp.array;
import java.util.Arrays;
public class SecondLargestNumInArray {
	 public static void main(String[] args)
	 {
	  int studentRollNo[] = new int[] {101,21,45,51,19,2};
	  // Call Arrays.sort() method 
	  Arrays.sort(studentRollNo);
	  // Traverse the StudentRollNo Array till Second last element
	  for(int loop=0; loop < studentRollNo.length; loop++) {
	      // Print second last element
	      if(loop == studentRollNo.length- 2)
	          System.out.println(studentRollNo[loop]);
	  }
	 }
}

24. How to validate if a particular value exists in array object in java ?

We can utilise the below array method to get the value from array object

Arrays.asList(<array object>).contains(<array element>);
package core.java.oracleappshelp.array;
import java.util.Arrays;
public class IsArrayValueExists {
	public static void main(String args[]) {
        String[]  studentNames = {"Roit", "Mohit", "Vinay", "Mohit", "Akshay" };
        System.out.println(isStudentExist(studentNames,"Mohit")); // true
        System.out.println(isStudentExist(studentNames,"Ajay")); // false
    }
    public static boolean isStudentExist(final String[] studentNames, final String value) {
        return Arrays.asList(studentNames).contains(value);
    }
}

25. Which is legal array initialization – int[] studentId or int studentId[] ?

Both are legal array initialization in java  . Preferred one is int[] studentId

Java Array program to find array elements with given sum

The java array program receives the list of unsorted array elements and sum value as input to the program. The array elements will be traversed and adds the sum of array elements at respective array index to compare if that equals to the sum value received as an input. If value matches at array index, the program will print the indexes else print “Array Element Pair not found”

Example:

    int[] ArrayObjList = { 2, 8, 4, 6, 12, 17 };
    int ArrayTotal = 20;

Here , the index 1 and index 4 sum is equal to the given sum.

package core.java.oracleappshelp.array;
public class ArrayPairSumEqualToArraySum {
		private static void findPair(int[] ArrayWithAllElements, int sum) {
		{
			// Traverse for Array Object till Array length -1
			for (int outerLoop = 0; outerLoop < ArrayWithAllElements.length - 1; outerLoop++)
			{
				// Traverse for the InnerLoop till last element
				for (int innerLoop = outerLoop + 1; innerLoop < ArrayWithAllElements.length; innerLoop++)
				{
					// check if the 2 compared elements sum is equal to the Array Sum
					if (ArrayWithAllElements[outerLoop] + ArrayWithAllElements[innerLoop] == sum)
					{
						System.out.println("Element Pair found at index " + innerLoop + " and " + outerLoop);
						return;
					}
				}
			}
			// When no array element is qualified 
			System.out.println("Array Element Pair not found");
		}
		}
		public static void main (String[] args){
			int[] ArrayObjList = { 2, 8, 4, 6, 12, 17 };
			int ArrayTotal = 20;
			findPair(ArrayObjList, ArrayTotal);
		}
	}
Array Program Output: 
Element Pair found at index 4 and 1    

MongoDB Database operations- Create Database, Drop Database

The tutorial provides the steps and mongoDB shell command execution to create database in MongoDB, drop database in MongoDB , create and drop statements in MongoDB with examples.

Follow the steps provided in Install MongoDB on Windows Server, Start MongoDB using MongoDB Shell.

Create Database Statement in MongoDB

The MongoDB provides the below given command to create the database. The command will create the New Database if doesn’t exist , else it returns the existing database. MongoDB uses default database as test for storing the documents if no database is created.

Syntax: use DATABASE_NAME

use oracleappshelpDB
switched to db oracleappshelpDB

Command to select the created database oracleappshelpDB

db
oracleappshelpDB

Command to get the list of all database in the MongoDB

show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

The created database oracleappshelpDB is not listed as we need to have atleast 1 document to be inserted

db.movie.insert({"name":"oracleappshelp.com MongoDB Create Database Tutorial"})
WriteResult({ "nInserted" : 1 })
> show dbs
admin             0.000GB
config            0.000GB
local             0.000GB
oracleappshelpDB  0.000GB

Drop Database statement in MongoDB

The below given command can be used for dropping the database from MongoDB

db.dropDatabase() 

As we are using oracleappshelpDB and inserted the document , thus current database in selection is oracleappshelpDB . If we execute the command db.dropDatabase() it will remove the database. In case of no specified database, the command will delete the default database “test”.

Execute the show dbs and use oracleappshelpDB command to switch to the required database which needs to be dropped.

show dbs
admin             0.000GB
config            0.000GB
local             0.000GB
oracleappshelpDB  0.000GB
> use oracleappshelpDB
switched to db oracleappshelpDB

Now, execute db.dropDatabase() command and then show dbs to ensure database is not shown now

> db.dropDatabase()
{ "dropped" : "oracleappshelpDB", "ok" : 1 }
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

How to download & Install mongodb on Windows ?

The tutorial provides the step by step process for installing MongoDB on windows 10.

  • Download MongoDB from community site: Click on the Download MongoDB link and get the on-premises installer from the community site (mongodb-win32-x86_64-2012plus-4.2.8-signed)
Download Mongodb
Download MongoDB

Start the installer: Click on the msi windows 64-bit installer ( mongodb-win32-x86_64-2012plus-4.2.8-signed ). Click Next and Accept the License Agreement Terms checkbox.

MongoDB Installer
MongoDB Installer

Select Components: Click on “complete” button to install all the required MongoDB components.

Select MongoDB components
Select MongoDB components

Service Configuration: Select option as “Run Service as a Network Service user” . Click Next.

MongoDB Service Configuration
MongoDB Service Configuration

Install MongoDB compass: Click Next to start the installation for MongoDB compass

MongoDB compass Installation
MongoDB Installation readiness

MongoDB Installation Progress: The below screen shows the MongoDB installation progress.

MongoDB Installation progress
MongoDB Installation progress

Click Finish when the installation is completed.

MongoDB compass is the non-commercial interactive GUI for managing the MongoDB Structure , querying the available data with the data representation.

  • Interactive editor for displaying document structure
  • Provides visual explain plans
  • Provides index management
  • Provides editing with validation of individual BSON types
  • Provides replica set connection to avoid fail over
  • Provides Query history

MongoDB compass provides the privacy setting to be enabled to provide various reports for MongoDB Data crash, MongoDB Data Statistics and MongoDB automatic updates.

MongoDB Compass Privacy Settings
MongoDB Compass Privacy Settings

Starting MongoDB in windows

As MongoDB generated documents , it requires the data folder to be specified to store its file. Create the data folder in C:/

C:\>md data
C:\md data\db

Now we need to provide this data folder location while running the MongoDB exe as given below

C:\Program Files\MongoDB\Server\4.2\bin
C:\Program Files\MongoDB\Server\4.2\bin>mongod.exe --dbpath "C:\data" 

Execute the below command to start the MongoDB shell:

C:\Program Files\MongoDB\Server\4.2\bin>mongo.exe

Install Python Driver for using MongoDB

  • Python should be installed on the system as the prerequisite. PIP should be preferred for installing pymongo ( driver for MongoDB)
  • Execute the below command to install Python driver for using MongoDB NoSQL Database
  • PyMongo supports CPython 2.7, 3.4+, PyPy, and PyPy3.5+.
 $ python -m pip install pymongo    (command for install pymongo driver) 
$ python -m pip install --upgrade pymongo   (command to upgrade pymongo driver) 

Install Ruby Driver for using MongoDB

  • Ruby should be installed on the system as the prerequisite
  • Execute the below command to install Ruby driver for using MongoDB NoSQL Database

Install Java Driver for using MongoDB

The MongodB provides the 2 maven artifacts for using MongoDB with the java driver.

mongodb-driver-legacy driver:It is the synchronous legacy driver

Entry point – com.mongodb.MongoClient

Central classes – com.mongodb.DB, com. mongodb.DBCollection, and com.mongodb.DBCursor

mongodb-driver-sync driver: It is the synchronous Java driver which provides the generic MongoCollection interface that complies with a new cross-driver CRUD operations.

Module Name – org.mongodb.driver.sync.client

The mongodb-driver-sync artifact is a valid OSGi bundle whose symbolic name is org.mongodb.driver-sync

Dependency: Add the below dependency in Java application for using MongoDB driver

 <dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver-sync</artifactId>
        <version>4.0.4</version>
    </dependency>
</dependencies>

MongoDB data types

The tutorial provides the commonly used data types available in the MongoDB NoSQL Database.

MongoDB allows to store different fields with different content and size in the document and uses the below given data types for the same.

MongoDB Data Type Data Type Description
Integer use to store integer value . Integer can be 32-bit or 64-bit
Doubleuse to store double (floating) values
Stringuse to store string values which must be UTF-8 valid in MongoDB
Boolean use to store boolean (true/false) values
Date use to store current date and time in unix time format
TimeStamp use to store timestamp for record creation /updation
Arraysuse to store multiple list /values or arrays into a single key
Min Max Keysuse to compare a value against the lowest and highest BSON elements
Objectuse to store embedded documents
Symboluse to store specific symbol type
Nulluse to store NULL value
Binary Data use to store binary data
Code use to store javaScript code into document
Regular Expressions use to store regular expressions

MongoDB NoSql Database Overview

The blog discuss on the common topics like What is MongoDB NoSQL Database ? What is document-oriented database ? Why MongoDB NoSQL Database is preferred than traditional RDBMS Database ?

What is NoSQL Database ?

The IT applications were extensively using the Relational databases like Oracle, SQL Server, MySQL for storing and retrieving the data. But with the upcoming trend of mobile applications like Facebook, Twitter and increasing demand for online shopping, has changed the trend of how application were managing and updating the application and customer data. In Relational Database, we need to create schemas, table, Indexes , define attribute data types, etc for database operations like create, update and delete records.

NoSQL database doesn’t requires these operations as prerequisite and can be executed on the fly to create, update and delete records which makes it easier to use and provides high performance.

What is MongoDB Database?

The MongoDB database is a cross platform NoSQL document-oriented database used for high volume data storage. MongoDB is an open -source database developed by the company 10gen. MongoDB was released in March 2010.

Why MongoDB ?

The MongoDB being a document-oriented database where database is a physical container for collections (set of file in the file system) whereas RDBMS Database consider each table data as a storing element. A collection is a group of documents with different fields maintained in the database with no enforced schema. The documents in the collection maintains a key-value pair which makes it useful for storing dynamic data (storing field with different types and structure). The key-value pair in MongoDB helps in providing high performance and scalability. The below given are the MongoDB features:

  • MongoDB is schema -less as it is document-oriented database using collections for storing documents
  • MongoDB allows to store different fields with different content and size in the document
  • MongoDB avoids complex joins for retrieving the data
  • MongoDB provides dynamic query for document data retrieval
  • MongoDB is scalable
  • MongoDB provides high performance
  • MongoDB is easy to use
  • MongoDB is light weight
  • MongoDB is much faster when compared with Relational Databases
  • provides Auto-sharding for horizontal scalability
  • provides built in replication for high availability

Difference between RDBMS and MongoDB ?

RDBMS DatabaseMongoDB Database
Relational Database requires schema, table creation, indexes, define attribute types to create, update and delete records MongoDB allows to create, update and delete records on the fly and does not require table structure.
RDBMS is a heavy weight Database MongoDB is a light weight database
RDBMS uses table as storing elementsMongoDB uses collections for storing documents
RDBMS supports multiple schema MongoDB stores dynamic data using documents and supports JSON format
RDBMS is slow when used for big and complex data MongoDB is much faster for big and complex data

Hardware Virtualization tutorial in cloud computing

The tutorial provides the hardware virtualization concepts, advantages of hardware virtualization in the cloud computing environment The tutorial is useful for both beginners and professionals.

What is hardware virtualization ?

The hardware virtualization is the mechanism through which multiple simulated environments or dedicated resources are shared from a single physical hardware . Hardware Virtualization can be achieved by installing HyperVisor as an abstraction layer between the software application and the physical hardware. HyperVisor creates isolated instances called as “Virtual machines” where each VM is installed with Operating System and Software Application to run independently without impacting other running VMs.

The hardware virtualization not only allows to install multiple applications on the single physical server but it alos allows to utilize the maximum physical server capacity which was underutilized on physical servers without virtualization. As each VM runs independently , it allows provided high server performance even though deployed with multiple applications.

Harware Virualization example: VMWare , Microsoft Hyper -V

Virtualization diagram
                                                Virtualization diagram

Advantages of Hardware Virtualization

  • Maximum utilization of server resources
  • Reduces the overall hardware cost
  • Provides highly orchestrated operations to ensure maximum uptime
  • Provides Easy application deployment process