MongoDB Tutorial PDF
MongoDB Tutorial PDF
MongoDB
TUTORIAL
Small Codes
Programming Simplified
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, SmlCodes.com, nor its dealers or
distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.
Smlcodes.com has endeavored to provide trademark information about all the companies
and products mentioned in this book by the appropriate use of capitals. However,
SmlCodes.com Publishing cannot guarantee the accuracy of this information.
If you discover any errors on our website or in this tutorial, please notify us at
[email protected] or [email protected]
Author Credits
Name : Satya Kaveti
Email : [email protected]
Digital Partners
2|P A G E
......................................................................................................................................................................................... 1
TUTORIAL .......................................................................................................................................................................................... 1
MONGODB TUTORIAL ....................................................................................................................................................................... 1
1. INTRODUCTION ........................................................................................................................................... 4
REFERENCES .................................................................................................................................................. 28
3|P A G E
1. Introduction
MongoDB is an open-source NoSQL, Document Database Written in C++ that provides high
performance, high availability, and automatic scaling.
4|P A G E
1.2 Document Database
A record in MongoDB is a document, which is a data structure composed of field and value pairs.
MongoDB documents are similar to JSON objects. The values of fields may include other documents,
arrays, and arrays of documents.
Rich Query Language : supports CRUD Operation, Data Aggregation, Text Search &Geospatial Queries.
High Availability : MongoDB’s replication facility, called replica set provide atomatic failover and
Data redundancy.
5|P A G E
Create a mongodb config file under : d:\mongodb\mongo.config
##store data here
dbpath=D:\mongodb\data
6|P A G E
2. MongoDB Operations
2.1 Database – Collection – Documents
Document: is a single entry / record. i.e., row in a database
Collection: Group of Documents are known as Collection. i.e., Table
Database: Group of Collections are known as Database
1. Create Database
Syntax:
> use smlcodes
switched to db smlcodes
Here, your created database "smlcodes" is not present in the list, insert at least one document into it to
display database
4. Drop Database
Syntax:
7|P A G E
> db.dropDatabase()
{ "dropped" : "smlcodes", "ok" : 1 }
Example: Insert a document named “admin” into a collection named “users”. The operation will create the
collection if the collection does not currently exist
> db.users.insert({"username":"admin", "password":"Admin@123"})
WriteResult({ "nInserted" : 1 })
> show collections
users
1. Create Collection
Syntax:
Name: is a string type, specifies the name of the collection to be created.
Options: is a document type, specifies the memory size and indexing of the collection. (optional)
> db.createCollection("books")
{ "ok" : 1 }
3. Drop Collection
Syntax:
> db.books.drop();
true
> show collections
users
The drop command returns true if it successfully drops a collection. It returns false when there is no
existing collection to drop.
8|P A G E
2.4 Document Operations
Data Types Description
String String is the most commonly used datatype. It is used to store data
Integer Integer is used to store the numeric value. It can be 32 bit or 64 bit depends on server
Boolean This datatype is used to store boolean values. It just shows YES/NO values.
Min/Max Keys This datatype compare a value against the lowest and highest bson elements.
Arrays This datatype is used to store a list or multiple values into a single key.
Date This datatype stores the current date or time in unix time format
If the collection does not currently exist, insert operations will create the collection.
_id Field: In MongoDB, each document stored in a collection requires a unique _id field that acts as a
primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an
ObjectId for the _id field.
1.db.collection.insert():
Inserts a single document or multiple documents into a collection. To insert a single document, pass a
document to the method; to insert multiple documents, pass an array of documents to the method
db.users.insert(
{
username: "Satya",
password: "Satya@134",
age:27,
status:"active"
}
)
WriteResult({ "nInserted" : 1 })
9|P A G E
2.db.collection.insertOne()
3.db.collection.insertMany()
Syntax
10 | P A G E
1.Select All Documents in a Collection
An empty query filter document ({}) selects all documents in the collection
Syntax
> db.users.find({})
{ "_id" : ObjectId("58986156fb8a774546289d9e"), "username" : "admin", "password" :
"Admin@123" }
{ "_id" : ObjectId("58986716fb8a774546289d9f"), "username" : "Satya", "password" :
"Satya@134", "age" : 27, "status" : "active" }
{ "_id" : ObjectId("58986791fb8a774546289da0"), "username" : "Smlcodes", "password" :
"Smlcodes@134", "age" : 27, "status" : "active" }
{ "_id" : ObjectId("589868c4fb8a774546289da1"), "username" : "Surya", "password" :
"Password@1345", "age" : 42, "status" : "inactive" }
Retrieves all documents where status equals "active" and age is less than ($lt) 30:
> db.users.find( { status: "active", age: { $lt: 30 } } )
{ "_id" : ObjectId("58986716fb8a774546289d9f"), "username" : "Satya", "password" :
"Satya@134", "age" : 27, "status" : "active" }
{ "_id" : ObjectId("58986791fb8a774546289da0"), "username" : "Smlcodes", "password" :
"Smlcodes@134", "age" : 27, "status" : "active" }
Retrieves all documents where the status equals "inactive" or age is less than ($lt) 30:
db.users.find(
{
$or: [ { status: "inactive" }, { age: { $lt: 30 } } ]
}
)
-------
{ "_id" : ObjectId("58986716fb8a774546289d9f"), "username" : "Satya", "password" :
"Satya@134", "age" : 27, "status" : "active" }
{ "_id" : ObjectId("589868c4fb8a774546289da1"), "username" : "Surya", "password" :
"Password@1345", "age" : 42, "status" : "inactive" }
For more related Query Documents visit MongoDB Offcial website
11 | P A G E
2.4.3 Update Documents
MongoDB provides the following methods for updating documents in a collection
1. db.collection.update()
2. db.collection.updateOne()
3. db.collection.updateMany()
4. db.collection.replaceOne()
1.db.collection.update()
Either updates or replaces a single document that match a specified filter or updates all documents that
match a specified filter.
db.users.update(
{ "status": "inactive" },
{
$set: { "Level": 2}
}
)
------
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
2.db.collection.updateOne()
Updates at most a single document that match a specified filter even though multiple documents may
match the specified filter.
db.users.updateOne(
{ "username": "Surya" },
{
$set: { "password": "901290190", age: 20 }
}
)
------
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
3.db.collection.updateMany()
Update all documents that match a specified filter.
db.users.updateMany(
{ "status": "active" },
{
$set: { "Level": 1}
}
)
----------
{ "acknowledged" : true, "matchedCount" : 6, "modifiedCount" : 6 }
12 | P A G E
4.db.collection.replaceOne()
Replaces at most a single document that match a specified filter even though multiple documents may
match the specified filter.
Delete operations do not drop indexes, even if deleting all documents from a collection
1.db.collection.remove()
To remove all documents from the collection based on condition
> db.users.remove( { age: 27 } )
WriteResult({ "nRemoved" : 2 })
2.db.collection.deleteOne()
Delete at most a single document that match a specified filter,even though multiple documents may
match
> db.users.deleteOne( { status: "active" } )
"acknowledged" : true, "deletedCount" : 1 }
3.db.collection.deleteMany()
To remove all documents from the collection based on condition
> db.users.deleteMany({ status : "inactive" })
"acknowledged" : true, "deletedCount" : 5 }
db.collection.findOneAndDelete().
findOneAndDelete() provides a sort option. The option allows for the deletion of the first
document sorted by the specified order.
db.collection.findOneAndModify().
db.collection.findOneAndModify() provides a sort option. The option allows for the deletion of
the first document sorted by the specified order.
db.collection.bulkWrite().
13 | P A G E
2.4.5 Advanced Operations
limit() To limit the records in MongoDB, you need to use limit() method
>db.COLLECTION_NAME.find().limit(NUMBER)
sort() specify sorting order. 1 is used for ascending order while -1 is used for descending order.
>db.COLLECTION_NAME.find().sort({KEY:1})
db.collection.save()
Updates an existing document or inserts a new document, depending on its document parameter.
db.products.save( { item: "book", qty: 40 } )
14 | P A G E
3. MongoDB with Java
To use MongoDB in our Java programs, we need MongoDB JDBC driver. Follow the below steps to do so.
1.Create Java Project using Elipse Convet that into Maven Project
if (mongo != null) {
System.out.println("============\n MongoDB Connected!!! \n===========");
System.out.println("Database Name : " + db.getName());
System.out.println("Collection : " + table.getName());
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
Output
MongoDB Connected!!!
===========
Database Name : smlcodes
Collection : user
15 | P A G E
3.1 MongoDB with Java
1.Mongo Connection
Connect to MongoDB server. For MongoDB version >= 2.10.0, uses MongoClient.
// Old version, uses Mongo
Mongo mongo = new Mongo("localhost", 27017);
2.Mongo Database
Get database. If the database doesn’t exist, MongoDB will create it for you.
DB db = mongo.getDB("database name");
3.Mongo Collection
16 | P A G E
1.Connect with MongoDB Server
MongoClient mongoClient = new MongoClient("localhost", 27017);
Example
import com.mongodb.DB;
import com.mongodb.MongoClient;
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
17 | P A G E
package core;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
public class MongoDB_Insert {
public static void main(String[] args) {
try {
// 1. BasicDBObject example
System.out.println("1.BasicDBObject example...");
System.out.println("===========================");
BasicDBObject document = new BasicDBObject();
document.put("username", "satyajohnny");
document.put("password", "password254");
// 2. BasicDBObjectBuilder example
System.out.println("\n\n 2.BasicDBObjectBuilder Insert");
System.out.println("===========================");
BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
.add("username", "Anil")
.add("password", "Anigirekula123");
// 3. Map example
System.out.println("\n\n 3.MAP Insert");
System.out.println("===========================");
Map<String, Object> documentMap = new HashMap<String, Object>();
documentMap.put("username", "mapuser");
documentMap.put("password", "mapassword");
18 | P A G E
Map<String, Object> documentMapDetail = new HashMap<String, Object>();
documentMapDetail.put("street", "JAMES STREET");
documentMapDetail.put("city", "GEORGIO");
documentMapDetail.put("state", "U.S");
documentMap.put("detail", documentMapDetail);
collection.insert(new BasicDBObject(documentMap));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
//Output
1.BasicDBObject example...
===========================
{ "_id" : { "$oid" : "589b07a32989f6de61c17c09"} , "username" : "satyajohnny" , "password" :
"password254" , "address" : { "street" : "RAMALAYAM" , "city" : "VIJAYAWADA" , "state" : "ANDHRA
PRADESH"}}
2.BasicDBObjectBuilder Insert
===========================
{ "_id" : { "$oid" : "589b07a32989f6de61c17c0a"} , "username" : "Anil" , "password" :
"Anigirekula123" , "detail" : { "street" : "NTR STREET" , "city" : "HYDERABAD" , "state" : "TN"}}
3.MAP Insert
===========================
{ "_id" : { "$oid" : "589b07a32989f6de61c17c0b"} , "password" : "mapassword" , "detail" : { "city"
: "GEORGIO" , "street" : "JAMES STREET" , "state" : "U.S"} , "username" : "mapuser"}
4.JSON Insert
===========================
{ "_id" : { "$oid" : "589b07a32989f6de61c17c0c"} , "username" : "jsonuser" , "password" :
"JsonPass" , "detail" : { "street" : "FIGHTCLUB STREET" , "city" : "MELBORN" , "state" : "AUS"}}
19 | P A G E
Similarly we can perform CURD operations using below methods in the same way
Update Operation
Update a document where “username”=”satya” to SatyaKaveti.
DBCollection table = db.getCollection("user");
table.update(query, updateObj);
Find/Query/Search Operation
Find document where “username =satya”, and display it with DBCursor
DBCollection table = db.getCollection("user");
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
Delete Operation
Find document where “username =satya”, and delete it.
DBCollection table = db.getCollection("user");
table.remove(searchQuery);
20 | P A G E
3.2 MongoDB with Spring Data
To work with MogoDB with Spring Data, we need following dependencies. So, add these dependencies in
pom.xml of your project & run maven install
<dependencies>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>
import com.mongodb.MongoClient;
@Configuration
public class SpringMongoConfig {
2. We need to create an Employee.java Bean class. Uses @Document to define a “collection name” when
you save this object. In this case, when “Employee” object saves, it will save into “employee” collection
package spring;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
21 | P A G E
@Document(collection = "employee")
public class Employee {
@Id
private String id;
public Employee(String id, String email, String name, int age, String address) {
super();
this.id = id;
this.email = email;
this.name = name;
this.age = age;
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", email=" + email + ",
name=" + name + ", age=" + age + ", address=" + address + "]";
}
}
Above SpringMongoConfig.java,Employee.java classes are common for all Examples
22 | P A G E
In Spring data MongoDB, you can use save(), insert() to save objects into mongoDB database.
User user = new User("...");
package spring;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
23 | P A G E
//Output
1 - insert a Employee, put 'employee' as collection name
2- insert a Emmployee, put bean name as collection name
3 - insert a list of employees
List Of all Saved Employees
===================
User [id=101, [email protected], name=AKHIL, age=30, address=Hyderabad]
User [id=102, [email protected], name=BALU, age=25, address=Vijayawada]
User [id=103, [email protected], name=CHANDU, age=35, address=Mumbai]
User [id=104, [email protected], name=DELIP, age=43, address=Delhi]
User [id=105, [email protected], name=ERVIN, age=29, address=Kolkata]
In spring data – MongoDB, you can use following methods to update documents.
1. save – Update the whole object, if “_id” is present, perform an update, else insert it.
2. updateFirst – Updates the first document that matches the query.
3. updateMulti – Updates all documents that match the query.
4. Upserting – If no document that matches the query, a new document is created by combining the
query and update object.
5. findAndModify – Same with updateMulti, but it has an extra option to return either the old or newly
updated document
package spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
24 | P A G E
System.out.println("1- find and update");
Query query1 = new Query();
query1.addCriteria(Criteria.where("name").is("BALU"));
Employee emp1 = mongoOperation.findOne(query1, Employee.class);
System.out.println("Before Update : " + emp1);
emp1.setAge(75);
mongoOperation.save(emp1);
Employee emp1_1 = mongoOperation.findOne(query1, Employee.class);
System.out.println("After Update : " + emp1_1 + "\n------------------");
//Output
1- find and update
Before Update : User [id=102, [email protected], name=BALU, age=75, address=Vijayawada]
After Update : User [id=102, [email protected], name=BALU, age=25, address=Vijayawada]
------------------
2- select single field only
Before Update : User [id=103, email=null, name=CHANDU, age=88, address=null]
After Update : User [id=103, email=null, name=CHANDU, age=38, address=null]
Here we show you a few examples to query documents from MongoDB, by using Query, Criteria and
along with some of the common operators.
1. BasicQuery example: If you are familiar with the core MongoDB console find() command, just put the
“raw” query inside the BasicQuery.
2. findOne example: findOne will return the single document that matches the query, and you can a
combine few criteria with Criteria.and()method. See example 4 for more details.
3. find and $inc example:Find and return a list of documents that match the query. This example also
shows the use of $inc operator.
4. find and $gt, $lt, $and example:Find and return a list of documents that match the query. This
example also shows the use of $gt, $lt and $and operators.
25 | P A G E
package spring;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
query4.addCriteria(Criteria.where("age").lt(40).andOperator(Criteria.where("age").gt(10)));
List<Employee> emp4 = mongoOperation.find(query4, Employee.class);
System.out.println("query4 - " + query4.toString());
for (Employee employee : emp4) {
System.out.println("emp4 - " + employee);
}
System.out.println("-----------------------------");
26 | P A G E
//Output
1 - findOne- with BasicQuery example
query1 - Query: { "age" : { "$lt" : 40}}, Fields: null, Sort: { }
emp1 - User [id=101, [email protected], name=AKHIL, age=30, address=Hyderabad]
-----------------------------
2 - findOne AND example
query2 - Query: { "name" : "DELIP" , "age" : 43}, Fields: null, Sort: null
emp2 - User [id=104, [email protected], name=DELIP, age=43, address=Delhi]
-----------------------------
3 - findlist $and $lt, $gt example
query4 - Query: { "age" : { "$lt" : 40} , "$and" : [ { "age" : { "$gt" : 10}}]}, Fields: null, Sort: null
emp4 - User [id=101, [email protected], name=AKHIL, age=30, address=Hyderabad]
emp4 - User [id=102, [email protected], name=BALU, age=25, address=Vijayawada]
emp4 - User [id=103, email=null, name=CHANDU, age=38, address=null]
emp4 - User [id=105, [email protected], name=ERVIN, age=29, address=Kolkata]
-----------------------------
4 - find list and sorting example
query5 - Query: { "age" : { "$gte" : 20}}, Fields: null, Sort: { "age" : -1}
emp5 - User [id=104, [email protected], name=DELIP, age=43, address=Delhi]
emp5 - User [id=103, email=null, name=CHANDU, age=38, address=null]
emp5 - User [id=101, [email protected], name=AKHIL, age=30, address=Hyderabad]
emp5 - User [id=105, [email protected], name=ERVIN, age=29, address=Kolkata]
emp5 - User [id=102, [email protected], name=BALU, age=25, address=Vijayawada]
-----------------------------
5- find by regex example
query6 - Query: { "name" : { "$regex" : "A.*U" , "$options" : "i"}}, Fields: null, Sort: null
emp6 - User [id=102, [email protected], name=BALU, age=25, address=Vijayawada]
emp6 - User [id=103, email=null, name=CHANDU, age=38, address=null]
In Spring data for MongoDB, you can use remove() and findAndRemove() to delete documents from
MongoDB.
package spring;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
//Output
All users :
User [id=101, [email protected], name=AKHIL, age=30, address=Hyderabad]
User [id=102, [email protected], name=BALU, age=25, address=Vijayawada]
User [id=103, email=null, name=CHANDU, age=38, address=null]
User [id=105, [email protected], name=ERVIN, age=29, address=Kolkata]
ALL Employees DELETED
================
THE END MONGODB
==============
References
http://www.javatpoint.com/mongodb-tutorial
https://docs.mongodb.com/v3.2/tutorial/
http://www.mkyong.com/tutorials/java-mongodb-tutorials/
https://www.tutorialspoint.com/mongodb/mongodb_environment.htm
28 | P A G E