0% found this document useful (0 votes)
66 views28 pages

MongoDB Tutorial PDF

Uploaded by

Vijay Cris
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views28 pages

MongoDB Tutorial PDF

Uploaded by

Vijay Cris
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Introduction
  • MongoDB Operations
  • MongoDB with Java
  • References

/smlcodes /smlcodes /smlcodes

MongoDB
TUTORIAL

Small Codes
Programming Simplified

A [Link] Small presentation


In Association with [Link]

For more tutorials & Articles visit [Link]


1|P A G E

Copyright © 2016 [Link] All rights Reserved.


MongoDB Tutorial
Copyright © 2016 [Link]

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, [Link], nor its dealers or
distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.

[Link] has endeavored to provide trademark information about all the companies
and products mentioned in this book by the appropriate use of capitals. However,
[Link] Publishing cannot guarantee the accuracy of this information.

If you discover any errors on our website or in this tutorial, please notify us at
support@[Link] or smlcodes@[Link]

First published on FEB 2016, Published by [Link]

Author Credits
Name : Satya Kaveti

Email : satyakaveti@[Link]

Website : [Link], [Link]

Digital Partners

2|P A G E
......................................................................................................................................................................................... 1
TUTORIAL .......................................................................................................................................................................................... 1
MONGODB TUTORIAL ....................................................................................................................................................................... 1

1. INTRODUCTION ........................................................................................................................................... 4

1.1 NOSQL (NOT ONLY SQL) .......................................................................................................................................................... 4


1.2 DOCUMENT DATABASE ............................................................................................................................................................... 5
1.3 MONGODB FEATURES & ADVANTAGES.................................................................................................................................. 5
1.4 MONGDB INSTALLATION & CONFIGURATION ...................................................................................................................... 5

2. MONGODB OPERATIONS ........................................................................................................................... 7

2.1 DATABASE – COLLECTION – DOCUMENTS .............................................................................................................................. 7


2.2 DATABASE OPERATIONS ............................................................................................................................................................. 7
2.3 COLLECTION OPERATIONS ......................................................................................................................................................... 8
2.4 DOCUMENT OPERATIONS ........................................................................................................................................................... 9

3. MONGODB WITH JAVA ............................................................................................................................... 15

3.1 MONGODB WITH JAVA .............................................................................................................................................................. 16


3.2 MONGODB WITH SPRING DATA.............................................................................................................................................. 21

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.

1.1 NoSQL (Not Only SQL)


It provides a mechanism for storage and retrieval of data other than tabular relations model used in
relational databases. NoSQL database doesn’t use tables for storing data. It is generally used to store big
data and real-time web applications.

NoSQL Database Types


 Document databases: Documents can contain many different key-value pairs, or key-array pairs.
 Graph stores: are used to store networks of data, such as social connections.
 Key-value stores: simplest NoSQL databases. Every single item in the database is stored as an
attribute name (or 'key'), together with its value.
 Wide-column stores such as Cassandra and HBase are optimized for queries over large datasets, and
store columns of data together, instead of rows.

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.

1.3 MongoDB Features & Advantages


High Performance : Indexes support faster queries

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.

Horizontal Scalability : Sharding (partitioning) distributes data across a cluster of machines.

1.4 MongDB Installation & Configuration


The MongoDB does not require installation, just download and extracts the zip file, configure the data
directory and start it with command “mongod“.

 Download MongoDB and extract into some folder, ex: d:/mongodb

 Create following directories inside d:/mongodb


o D:\mongodb\data
o D:\mongodb\log
 Configure Environmnet variables MongoDB = D:\mongodb PATH=%MongoDB%\bin

5|P A G E
 Create a mongodb config file under : d:\mongodb\[Link]
##store data here
dbpath=D:\mongodb\data

##all output go here


logpath=D:\mongodb\log\[Link]

##log read and write operations


diaglog=3

 Start MongoDB using any of below commands


 D:\mongodb\bin>mongod –dbpath=D:/mongodb
 d:\mongodb\bin>[Link] --config="D:\mongodb\[Link]"

 Connect to MongoDB using mongo command

To start MongoDB Service


net start MongoDB

To stop MongoDB Service

net stop MongoDB

To remove MongoDB Service


c:\mongodb\bin>mongod --remove

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

2.2 Database Operations

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

2. Check the currently selected database


Syntax:
> db
Smlcodes

3. Show all Databases


Syntax:
> show dbs
local 0.000GB
smlcodes 0.000GB

4. Drop Database
Syntax:
7|P A G E
> [Link]()
{ "dropped" : "smlcodes", "ok" : 1 }

2.3 Collection Operations


Usually we don’t need to create collection. MongoDB creates collection automatically when you insert
some documents.

Example: Insert a document named “admin” into a collection named “users”. The operation will create the
collection if the collection does not currently exist
> [Link]({"username":"admin", "password":"Admin@123"})
WriteResult({ "nInserted" : 1 })
> show collections
users

We can also create collection by using

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)

> [Link]("books")
{ "ok" : 1 }

[Link] the collections in the database


Syntax:
> show collections
books
users

3. Drop Collection
Syntax:
> [Link]();
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.

Double Double datatype stores floating point 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.

Object Object datatype is used for embedded documents.

Null It is used to store null values.

Symbol It is generally used for languages that use a specific type.

Date This datatype stores the current date or time in unix time format

2.4.1 Insert Documents


MongoDB provides the following methods for inserting documents into a collection:
1. [Link]()
2. [Link]()
3. [Link]()

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.

[Link]():
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
[Link](
{
username: "Satya",
password: "Satya@134",
age:27,
status:"active"
}
)
WriteResult({ "nInserted" : 1 })
9|P A G E
[Link]()

Inserts a single document into a collection


> [Link](
{
username: "Smlcodes",
password: "Smlcodes@134",
age:27,
status:"active"
}
)
{
"acknowledged" : true,
"insertedId" : ObjectId("58986791fb8a774546289da0")
}

[Link]()

Inserts multiple documents into a collection.


[Link](
[
{ username:"Surya", password:"Password@1345", age: 42, status: "inactive", },
{ username:"Ravi", password:"Password@1345", age: 22, status: "inactive", },
{ username:"Rakesh", password:"Password@1345", age: 34, status: "active", }
]
)
----
... )
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("589868c4fb8a774546289da1"),
ObjectId("589868c4fb8a774546289da2"),
ObjectId("589868c4fb8a774546289da3")
]
}

2.4.2 Query Documents (find Operations)


MongoDB provides the [Link]() method to read documents from a collection. The
[Link]() method returns a cursor to the matching documents.

Syntax

 <query filter>: a query filter to specify which documents to return.


 < projection>: which fields from the matching documents to return

10 | P A G E
[Link] All Documents in a Collection
An empty query filter document ({}) selects all documents in the collection
Syntax
> [Link]({})
{ "_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" }

[Link] All Documents with Condition


> [Link]( { status: "active" } )
{ "_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("589868c4fb8a774546289da3"), "username" : "Rakesh", "password" :
"Password@1345", "age" : 34, "status" : "active" }

[Link] All Documents with AND Condition


We can specify the the no. of conditions by using comma (,) operator

Retrieves all documents where status equals "active" and age is less than ($lt) 30:
> [Link]( { 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" }

[Link] All Documents with OR Condition


Using the $or operator, you can specify a compound query that joins each clause with a logical OR
conjunction so that the query selects the documents in the collection that match at least one condition.

Retrieves all documents where the status equals "inactive" or age is less than ($lt) 30:
[Link](
{
$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. [Link]()
2. [Link]()
3. [Link]()
4. [Link]()

[Link]()
Either updates or replaces a single document that match a specified filter or updates all documents that
match a specified filter.

[Link](
{ "status": "inactive" },
{
$set: { "Level": 2}
}
)
------
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

[Link]()
Updates at most a single document that match a specified filter even though multiple documents may
match the specified filter.
[Link](
{ "username": "Surya" },
{
$set: { "password": "901290190", age: 20 }
}
)
------
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

[Link]()
Update all documents that match a specified filter.
[Link](
{ "status": "active" },
{
$set: { "Level": 1}
}
)
----------
{ "acknowledged" : true, "matchedCount" : 6, "modifiedCount" : 6 }

12 | P A G E
[Link]()
Replaces at most a single document that match a specified filter even though multiple documents may
match the specified filter.

2.4.4 Delete Documents


MongoDB provides the following methods to delete documents of a collection:
1. [Link]()
2. [Link]()
3. [Link]()

Delete operations do not drop indexes, even if deleting all documents from a collection

[Link]()
To remove all documents from the collection based on condition
> [Link]( { age: 27 } )
WriteResult({ "nRemoved" : 2 })

[Link]()
Delete at most a single document that match a specified filter,even though multiple documents may
match
> [Link]( { status: "active" } )
"acknowledged" : true, "deletedCount" : 1 }

[Link]()
To remove all documents from the collection based on condition
> [Link]({ status : "inactive" })
"acknowledged" : true, "deletedCount" : 5 }

The following methods can also delete documents from a collection:

 [Link]().
 findOneAndDelete() provides a sort option. The option allows for the deletion of the first
document sorted by the specified order.
 [Link]().
 [Link]() provides a sort option. The option allows for the deletion of
the first document sorted by the specified order.
 [Link]().

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)

Skip() used to skip the number of documents.


>db.COLLECTION_NAME.find().limit(NUMBER).skip(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})

aggregate() aggregation in MongoDB, you should use aggregate() method.


>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
AGGREGATE_OPERATION = $sum, $avg, $min, $max, $push, $addToSet, $first, $last

[Link]()
Updates an existing document or inserts a new document, depending on its document parameter.
[Link]( { item: "book", qty: 40 } )

help() uses to guide you how to do things in MongoDB.


[Link]() help on db methods
[Link]() help on collection methods
[Link]() sharding helpers
[Link]() replica set helpers
help admin administrative help
help connect connecting to a db help
help keys key shortcuts
help misc misc things to know
help mr mapreduce

show dbs show database names


show collections show collections in current database
show users show users in current database
show profile show most recent [Link] entries time >= 1ms
show logs show the accessible logger names
show log [name] prints out the last segment of log in memory,
use <db_name> set current database
[Link]() list objects in collection foo
[Link]( { a : 1 } ) list objects in foo where a == 1
it result of the last line evaluated; use to further
iterate
[Link] = x set default number of items to display on shell
exit quit the mongo shell

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.

[Link] Java Project using Elipse Convet that into Maven Project

2. Download mongo-java driver from github. Or declare mongo-java driver in [Link]


<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>

3. Write a Java class to connect with MongoDB & perform operations


package core;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MongoDBConnect {


public static void main(String[] args) {
try {
/**** Connect to MongoDB ****/
// Since 2.10.0, uses MongoClient
MongoClient mongo = new MongoClient("localhost", 27017);

/**** Get database ****/


// if database doesn't exists, MongoDB will create it for you
DB db = [Link]("smlcodes");

/**** Get collection / table from 'testdb' ****/


// if collection doesn't exists, MongoDB will create it for you
DBCollection table = [Link]("user");

if (mongo != null) {
[Link]("============\n MongoDB Connected!!! \n===========");
[Link]("Database Name : " + [Link]());
[Link]("Collection : " + [Link]());
}

} catch (UnknownHostException e) {
[Link]();
} catch (MongoException e) {
[Link]();
}
}
}

Output
MongoDB Connected!!!
===========
Database Name : smlcodes
Collection : user

15 | P A G E
3.1 MongoDB with Java

[Link] Connection
Connect to MongoDB server. For MongoDB version >= 2.10.0, uses MongoClient.
// Old version, uses Mongo
Mongo mongo = new Mongo("localhost", 27017);

// Since 2.10.0, uses MongoClient


MongoClient mongo = new MongoClient( "localhost" , 27017 );

[Link] Database
Get database. If the database doesn’t exist, MongoDB will create it for you.
DB db = [Link]("database name");

If MongoDB in secure mode, authentication is required


boolean auth = [Link]("username", "password".toCharArray());

Display all databases.


List<String> dbs = [Link]();
for(String db : dbs){
[Link](db);
}

[Link] Collection

Get collection / table.


DB db = [Link]("testdb");
DBCollection table = [Link]("user");

Display all collections from selected database.


DB db = [Link]("testdb");
Set<String> tables = [Link]();

for(String coll : tables){


[Link](coll);
}

16 | P A G E
[Link] with MongoDB Server
MongoClient mongoClient = new MongoClient("localhost", 27017);

[Link] with Database


DB db = [Link]("smlcodes");

[Link] the Collection , on which collection you want to work


DBCollection collection = [Link]("users");

[Link] Document Object to perform CURD operaions on Document


BasicDBObject document = new BasicDBObject();

Add user to smlcodes Collection for testing purpose


[Link](
{
user: "admin",
pwd: "admin",
roles: [
{role: "readWrite", db: "smlcodes"}
]
}
)

Example
import [Link];
import [Link];

public class MongoDB_Authentication {


public static void main(String args[]) {
try {
// To connect to mongodb server
MongoClient mongoClient = new MongoClient("localhost", 27017);

// Now connect to your databases


DB db = [Link]("smlcodes");
[Link]("Connect to database successfully");
boolean auth = [Link]("admin", "admin".toCharArray());
[Link]("Authentication: " + auth);

} catch (Exception e) {
[Link]([Link]().getName() + ": " + [Link]());
}
}
}

17 | P A G E
package core;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MongoDB_Insert {
public static void main(String[] args) {

try {

Mongo mongo = new Mongo("localhost", 27017);


DB db = [Link]("smlcodes");

DBCollection collection = [Link]("users");


[Link](new BasicDBObject());

// 1. BasicDBObject example
[Link]("[Link] example...");
[Link]("===========================");
BasicDBObject document = new BasicDBObject();
[Link]("username", "satyajohnny");
[Link]("password", "password254");

BasicDBObject documentDetail = new BasicDBObject();


[Link]("street", "RAMALAYAM");
[Link]("city", "VIJAYAWADA");
[Link]("state", "ANDHRA PRADESH");
[Link]("address", documentDetail);
[Link](document);

DBCursor cursorDoc = [Link]();


while ([Link]()) {
[Link]([Link]());
}
[Link](new BasicDBObject());

// 2. BasicDBObjectBuilder example
[Link]("\n\n [Link] Insert");
[Link]("===========================");
BasicDBObjectBuilder documentBuilder = [Link]()
.add("username", "Anil")
.add("password", "Anigirekula123");

BasicDBObjectBuilder documentBuilderDetail = [Link]()


.add("street", "NTR STREET")
.add("city", "HYDERABAD").add("state", "TN");
[Link]("detail", [Link]());
[Link]([Link]());

DBCursor cursorDocBuilder = [Link]();


while ([Link]()) {
[Link]([Link]());
}
[Link](new BasicDBObject());

// 3. Map example
[Link]("\n\n [Link] Insert");
[Link]("===========================");
Map<String, Object> documentMap = new HashMap<String, Object>();
[Link]("username", "mapuser");
[Link]("password", "mapassword");

18 | P A G E
Map<String, Object> documentMapDetail = new HashMap<String, Object>();
[Link]("street", "JAMES STREET");
[Link]("city", "GEORGIO");
[Link]("state", "U.S");
[Link]("detail", documentMapDetail);
[Link](new BasicDBObject(documentMap));

DBCursor cursorDocMap = [Link]();


while ([Link]()) {
[Link]([Link]());
}
[Link](new BasicDBObject());

// 4. JSON parse example


[Link]("\n\n [Link] Insert");
[Link]("===========================");

String json = "{'username' : 'jsonuser','password' : 'JsonPass',"


+ "'detail' : {'street' : 'FIGHTCLUB STREET', 'city' : 'MELBORN', 'state' : 'AUS'}}}";

DBObject dbObject = (DBObject) [Link](json);


[Link](dbObject);

DBCursor cursorDocJSON = [Link]();


while ([Link]()) {
[Link]([Link]());
}
[Link](new BasicDBObject());

} catch (UnknownHostException e) {
[Link]();
} catch (MongoException e) {
[Link]();
}

}
}

//Output
[Link] example...
===========================
{ "_id" : { "$oid" : "589b07a32989f6de61c17c09"} , "username" : "satyajohnny" , "password" :
"password254" , "address" : { "street" : "RAMALAYAM" , "city" : "VIJAYAWADA" , "state" : "ANDHRA
PRADESH"}}

[Link] Insert
===========================
{ "_id" : { "$oid" : "589b07a32989f6de61c17c0a"} , "username" : "Anil" , "password" :
"Anigirekula123" , "detail" : { "street" : "NTR STREET" , "city" : "HYDERABAD" , "state" : "TN"}}

[Link] Insert
===========================
{ "_id" : { "$oid" : "589b07a32989f6de61c17c0b"} , "password" : "mapassword" , "detail" : { "city"
: "GEORGIO" , "street" : "JAMES STREET" , "state" : "U.S"} , "username" : "mapuser"}

[Link] Insert
===========================
{ "_id" : { "$oid" : "589b07a32989f6de61c17c0c"} , "username" : "jsonuser" , "password" :
"JsonPass" , "detail" : { "street" : "FIGHTCLUB STREET" , "city" : "MELBORN" , "state" : "AUS"}}

In above we are removing inserted Object for display purpose only


[Link](new BasicDBObject());

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 = [Link]("user");

BasicDBObject query = new BasicDBObject();


[Link]("username", "satya");

BasicDBObject newDocument = new BasicDBObject();


[Link]("username", "SatyaKaveti");

BasicDBObject updateObj = new BasicDBObject();


[Link]("$set", newDocument);

[Link](query, updateObj);

Find/Query/Search Operation
Find document where “username =satya”, and display it with DBCursor
DBCollection table = [Link]("user");

BasicDBObject searchQuery = new BasicDBObject();


[Link]("username ", " satya ");

DBCursor cursor = [Link](searchQuery);

while ([Link]()) {
[Link]([Link]());
}

Delete Operation
Find document where “username =satya”, and delete it.
DBCollection table = [Link]("user");

BasicDBObject searchQuery = new BasicDBObject();


[Link]("username ", " satya ");

[Link](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
[Link] of your project & run maven install
<dependencies>
<!-- Spring framework -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-core</artifactId>
<version>[Link]</version>
</dependency>

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-context</artifactId>
<version>[Link]</version>
</dependency>

<!-- mongodb java driver -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.0</version>
</dependency>

<!-- Spring data mongodb -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>[Link]</version>
</dependency>

<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>

1. We need to create [Link] to connect with MongoDB database


package spring;
import [Link];
import [Link];
import [Link];

import [Link];

@Configuration
public class SpringMongoConfig {

public @Bean MongoTemplate mongoTemplate() throws Exception {


MongoTemplate mongoTemplate = new MongoTemplate(new MongoClient("[Link]"), "Emp");
return mongoTemplate;
}
}

2. We need to create an [Link] 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 [Link];
import [Link];
import [Link];
21 | P A G E
@Document(collection = "employee")
public class Employee {
@Id
private String id;

@Indexed // means Unique


private String email;

private String name;


private int age;
private String address;

public String getId() {


return id;
}

public void setId(String id) {


[Link] = id;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


[Link] = email;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


[Link] = age;
}

public String getAddress() {


return address;
}

public void setAddress(String address) {


[Link] = address;
}

public Employee(String id, String email, String name, int age, String address) {
super();
[Link] = id;
[Link] = email;
[Link] = name;
[Link] = age;
[Link] = address;
}

@Override
public String toString() {
return "User [id=" + id + ", email=" + email + ",
name=" + name + ", age=" + age + ", address=" + address + "]";
}

}
Above [Link],[Link] 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("...");

//save user object into "user" collection / table


//class name will be used as collection name
[Link](user);

//save user object into "users" collection


[Link](user,"users");

//insert user object into "user" collection


//class name will be used as collection name
[Link](user);

//insert user object into " users " collection


[Link](user, " users ");

//insert a list of user objects


[Link](listofUser);
 Save (saveOrUpdate()) it performs insert() if “_id” is NOT exist or update() if “_id” is existed”.
 Insert – Only insert, if “_id” is existed, an error is generated.

package spring;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class SpringMongo_Insert {

public static void main(String[] args) {


// For Annotation
ApplicationContext ctx = new AnnotationConfigApplicationContext([Link]);
MongoOperations mongoOperation = (MongoOperations) [Link]("mongoTemplate");

[Link]("1 - insert a Employee, put 'employee' as collection name");


Employee emp1 = new Employee("101", "[Link]@[Link]", "AKHIL", 30, "Hyderabad");
[Link](emp1, "employee");

[Link]("2- insert a Emmployee, put bean name as collection name");


Employee emp2 = new Employee("102", "[Link]@[Link]", "BALU", 25, "Vijayawada");
[Link](emp2);

[Link]("3 - insert a list of employees");


Employee emp3 = new Employee("103", "[Link]@[Link]", "CHANDU", 35, "Mumbai");
Employee emp4 = new Employee("104", "[Link]@[Link]", "DELIP", 43, "Delhi");
Employee emp5 = new Employee("105", "[Link]@[Link]", "ERVIN", 29, "Kolkata");
List<Employee> empList = new ArrayList<Employee>();
[Link](emp3);
[Link](emp4);
[Link](emp5);
[Link](empList, [Link]);

[Link]("List Of all Saved Employees \n===================");


List<Employee> employees = [Link]([Link]);

for (Employee employee : employees) {


[Link](employee);
[Link](employee);
}
}
}

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=[Link]@[Link], name=AKHIL, age=30, address=Hyderabad]
User [id=102, email=[Link]@[Link], name=BALU, age=25, address=Vijayawada]
User [id=103, email=[Link]@[Link], name=CHANDU, age=35, address=Mumbai]
User [id=104, email=[Link]@[Link], name=DELIP, age=43, address=Delhi]
User [id=105, email=[Link]@[Link], 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

Find the document, modify and update it with save() method.


Query query = new Query();
[Link]([Link]("name").is("appleA"));

User userTest1 = [Link](query, [Link]);

[Link]("userTest1 - " + userTest1);

//modify and update with save()


[Link](99);
[Link](userTest1);

//get the updated object again


User userTest1_1 = [Link](query, [Link]);

[Link]("userTest1_1 - " + userTest1_1);

package spring;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class SpringMongo_Update {

public static void main(String[] args) {


// For Annotation
ApplicationContext ctx = new AnnotationConfigApplicationContext([Link]);
MongoOperations mongoOperation = (MongoOperations) [Link]("mongoTemplate");

24 | P A G E
[Link]("1- find and update");
Query query1 = new Query();
[Link]([Link]("name").is("BALU"));
Employee emp1 = [Link](query1, [Link]);
[Link]("Before Update : " + emp1);
[Link](75);
[Link](emp1);
Employee emp1_1 = [Link](query1, [Link]);
[Link]("After Update : " + emp1_1 + "\n------------------");

[Link]("2- select single field only");


Query query2 = new Query();
[Link]([Link]("name").is("CHANDU"));
[Link]().include("name");
[Link]().include("age");
Employee emp2 = [Link](query2, [Link]);
[Link]("Before Update : " + emp2);
[Link](88);
[Link](emp2);
Employee emp11 = [Link](query2, [Link]);
[Link]("After Update : " + emp11 + "\n------------------");
}

//Output
1- find and update
Before Update : User [id=102, email=[Link]@[Link], name=BALU, age=75, address=Vijayawada]
After Update : User [id=102, email=[Link]@[Link], 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 [Link]()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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class SpringMongo_QueryFind {

public static void main(String[] args) {


// For Annotation
ApplicationContext ctx = new AnnotationConfigApplicationContext([Link]);
MongoOperations mongoOperation = (MongoOperations) [Link]("mongoTemplate");

[Link]("1 - findOne- with BasicQuery example");


BasicQuery query1 = new BasicQuery("{ age : { $lt : 40 } }");
Employee emp1 = [Link](query1, [Link]);
[Link]("query1 - " + [Link]());
[Link]("emp1 - " + emp1);
[Link]("-----------------------------");

[Link]("2 - findOne AND example");


Query query2 = new Query();
[Link]([Link]("name").is("DELIP").and("age").is(43));
Employee emp2 = [Link](query2, [Link]);
[Link]("query2 - " + [Link]());
[Link]("emp2 - " + emp2);
[Link]("-----------------------------");

[Link]("3 - findlist $and $lt, $gt example");


Query query4 = new Query();

[Link]([Link]("age").lt(40).andOperator([Link]("age").gt(10)));
List<Employee> emp4 = [Link](query4, [Link]);
[Link]("query4 - " + [Link]());
for (Employee employee : emp4) {
[Link]("emp4 - " + employee);
}
[Link]("-----------------------------");

[Link]("4 - find list and sorting example");


Query query5 = new Query();
[Link]([Link]("age").gte(20));
[Link](new Sort([Link], "age"));
List<Employee> emp5 = [Link](query5, [Link]);
[Link]("query5 - " + [Link]());
for (Employee employee : emp5) {
[Link]("emp5 - " + employee);
}
[Link]("-----------------------------");

[Link](" 5- find by regex example");


Query query6 = new Query();
[Link]([Link]("name").regex("A.*U", "i"));
List<Employee> emp6 = [Link](query6, [Link]);
[Link]("query6 - " + [Link]());
for (Employee user : emp6) {
[Link]("emp6 - " + user);
}
}
}

26 | P A G E
//Output
1 - findOne- with BasicQuery example
query1 - Query: { "age" : { "$lt" : 40}}, Fields: null, Sort: { }
emp1 - User [id=101, email=[Link]@[Link], 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=[Link]@[Link], 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=[Link]@[Link], name=AKHIL, age=30, address=Hyderabad]
emp4 - User [id=102, email=[Link]@[Link], name=BALU, age=25, address=Vijayawada]
emp4 - User [id=103, email=null, name=CHANDU, age=38, address=null]
emp4 - User [id=105, email=[Link]@[Link], 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=[Link]@[Link], name=DELIP, age=43, address=Delhi]
emp5 - User [id=103, email=null, name=CHANDU, age=38, address=null]
emp5 - User [id=101, email=[Link]@[Link], name=AKHIL, age=30, address=Hyderabad]
emp5 - User [id=105, email=[Link]@[Link], name=ERVIN, age=29, address=Kolkata]
emp5 - User [id=102, email=[Link]@[Link], 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=[Link]@[Link], 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.

 remove() – delete single or multiple documents.


 findAndRemove() – delete single document, and returns the deleted document.

package spring;

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class SpringMongo_Delete {

public static void main(String[] args) {


// For Annotation
ApplicationContext ctx = new AnnotationConfigApplicationContext([Link]);
MongoOperations mongoOperation = (MongoOperations) [Link]("mongoTemplate");

Query query1 = new Query();


[Link]([Link]("name").is("DELIP").and("age").is(43));
Employee emp2 = [Link](query1, [Link]);
[Link](query1, [Link]);
[Link]("\nAll users : ");
27 | P A G E
List<Employee> allEmployees = [Link]([Link]);
for (Employee user : allEmployees) {
[Link](user);
}
//[Link]([Link]);

[Link]("ALL Employees DELETED");


[Link]("================\n THE END MONGODB\n ==============");

//Output
All users :
User [id=101, email=[Link]@[Link], name=AKHIL, age=30, address=Hyderabad]
User [id=102, email=[Link]@[Link], name=BALU, age=25, address=Vijayawada]
User [id=103, email=null, name=CHANDU, age=38, address=null]
User [id=105, email=[Link]@[Link], name=ERVIN, age=29, address=Kolkata]
ALL Employees DELETED
================
THE END MONGODB
==============

References
[Link]

[Link]

[Link]

[Link]

28 | P A G E

Common questions

Powered by AI

Upserting is a database operation that combines updating and inserting behaviors. If a query finds a matching document, it updates that document; if no document matches, a new document is created using the query and update parameters. In Spring Data MongoDB, upserting is implemented in update operations where, through mechanisms like findAndModify or save(), the absence of a matching document prompts the creation of a new one, thus efficiently combining two operations into one .

The limit() method in MongoDB restricts the number of documents returned by a query, which is useful for pagination or when only a subset of data is needed, reducing load and improving performance. The skip() method allows the query to bypass a set number of documents, often used in conjunction with limit() for effective pagination. The sort() method orders the documents based on specified fields either in ascending (1) or descending (-1) order, enabling organized data retrieval and efficient display in client applications. Together, these methods provide a robust toolkit for managing large datasets .

db.collection.updateOne() updates at most a single document matching the specified filter, even if multiple documents could match. This is useful for operations where only a specific document should be updated. On the other hand, db.collection.updateMany() updates all documents that match the filter, which is suitable for bulk updates across multiple records. The choice between these methods depends on whether the update is meant to be precise (updateOne) or broad (updateMany), affecting performance and application logic accordingly .

Embedding documents in MongoDB collections is crucial for leveraging its schema-less flexibility, allowing related data to be stored together rather than normalized across several tables. This design eliminates the need for joins, enhances read performance, and reflects document-oriented patterns where entire data entities including nested structures can be queried together efficiently. This contrasts with traditional relational databases that require foreign keys and complex joins to retrieve related data spread across tables, which can be cumbersome and less performant .

Compound queries using $and and $or operators allow MongoDB to conduct complex searches by combining multiple conditions. The $and operator ensures that all specified conditions must be true for a document to be selected, while the $or operator allows for selection if any condition is true. For example, a query using $and might search for documents where the status is 'active' and the age is less than 30. Conversely, using $or could retrieve documents where the status is 'inactive' or the age is less than 30, providing flexibility in filtering and more targeted data retrieval .

The aggregation framework in MongoDB is significant as it supports complex data processing and transformation tasks in a streamlined manner. It allows for operations such as $sum, $avg, $min, $max, $push, $addToSet, $first, and $last, which aggregate data across documents to compute results such as totals, averages, and distinct values. This capability enables powerful queries to be executed directly within the database layer, reducing the need for client-side processing, thus optimizing performance and enhancing the expressiveness of queries .

db.collection.insert() can insert a single document or multiple documents at once by passing an array of documents, which makes it versatile for batch operations. However, db.collection.insertOne() is specifically designed to insert a single document, providing a simpler and more direct API for cases where a single insert operation is needed. This impacts data insertion strategies by allowing developers to choose the method that best fits the use case—optimized for single inserts or bulk operations .

In MongoDB, every document stored in a collection is required to have a unique _id field, which serves as the primary key. If a document is inserted without an explicitly set _id, MongoDB automatically generates an ObjectId for this field. This ensures data integrity by preventing duplicate entries and allows for efficient document retrieval .

findOneAndDelete() and findAndModify() provide atomic operations for managing documents by ensuring the document is found and modified or deleted as a single transaction. findOneAndDelete() retrieves and removes a document based on a query, ensuring atomicity by not requiring separate read and delete operations. Similarly, findAndModify() locates and updates documents with an additional option to return the updated or original document, optimizing performance by avoiding separate read-modify steps. Both methods enhance reliability by wrapping operations into atomic transactions .

db.collection.remove() deletes documents based on the given condition but can remove all documents if the condition matches them, making it powerful for bulk deletions. db.collection.deleteMany(), however, is specifically designed to remove multiple documents that match a condition, offering clarity in intent and functionality. The use of remove() might lead to ambiguity if the intent is unknown, whereas deleteMany() clearly communicates a multiple-document removal task .

1 | P A G E  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
     (https:/ (https://www.facebook.com/SmlCodes-216971275364320/)
2 | P A G E  
 
MongoDB Tutorial 
 
Copyright © 2016 Smlcodes.com 
All rights reserved. No part of this book may be reproduce
3 | P A G E  
 
 
 ..........................................................................................................
4 | P A G E  
 
1. Introduction 
MongoDB is an open-source NoSQL, Document Database Written in C++ that provides high 
perfor
5 | P A G E  
 
1.2 Document Database 
A record in MongoDB is a document, which is a data structure composed of field and val
6 | P A G E  
 
 
Create a mongodb config file under : d:mongodbmongo.config 
##store data here 
dbpath=D:mongodbdata
7 | P A G E  
 
 
2. MongoDB Operations 
2.1 Database – Collection – Documents 
 
Document: is a single entry / record. i.e.
8 | P A G E  
 
> db.dropDatabase() 
{ "dropped" : "smlcodes", "ok" : 1 } 
2.3 Collection Operations 
Usually we don’t need t
9 | P A G E  
 
 
2.4 Document Operations 
Data Types 
Description 
String 
String is the most commonly used datatype. It is
10 | P A G E  
 
2.db.collection.insertOne() 
 
Inserts a single document into a collection 
> db.users.insertOne( 
   {

You might also like