Unit 1
Unit 1
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 relies upon a softer model known as the BASE model. BASE (Basically
Available, Soft state, Eventual consistency).
- Basically Available: Guarantees the availability of the data . There will be a response
to any request (can be failure too).
- Soft state: The state of the system could change over time.
- Eventual consistency: The system will eventually become consistent once it stops
receiving input.
Features of NoSQL
Non-relational
NoSQL databases never follow the relational model
Never provide tables with flat fixed-column records
Work with self-contained aggregates or BLOBs
Doesn’t require object-relational mapping and data normalization
No complex features like query languages, query planners,referential integrity joins,
ACID
Schema-free
NoSQL databases are either schema-free or have relaxed schemas
Do not require any sort of definition of the schema of the data
Offers heterogeneous structures of data in the same domain
Simple API
Offers easy to use interfaces for storage and querying data provided
APIs allow low-level data manipulation & selection methods
Text-based protocols mostly used with HTTP REST with JSON
Mostly used no standard based NoSQL query language
Web-enabled databases running as internet-facing services
Distributed
Multiple NoSQL databases can be executed in a distributed fashion
Offers auto-scaling and fail-over capabilities
Often ACID concept can be sacrificed for scalability and throughput
Mostly no synchronous replication between distributed nodes Asynchronous Multi-
Master Replication, peer-to-peer, HDFS Replication
Only providing eventual consistency
Shared Nothing Architecture. This enables less coordination and higher distribution.
Highscalability –
NoSQL database use sharding for horizontal scaling.
High availability –
Auto replication feature in NoSQL databases makes it highly available because in
case of any failure data replicates itself to the previous consistent state.
Distributed Computing
Lower cost
Schema flexibility
Un/semi-structured data
No complex relationships
Disadvantages of NoSQL
No standardization rules
Limited query capabilities
RDBMS databases and tools are comparatively mature
It does not offer any traditional database capabilities, like consistency when multiple
transactions are performed simultaneously.
When the volume of data increases it is difficult to maintain unique values as keys
become difficult
Doesn’t work as well with relational data
The learning curve is stiff for new developers
Open source options so not so popular for enterprises.
SQL NoSQL
These databases are not suited for hierarchical These databases are best suited for
data storage. hierarchical data storage.
These databases are best suited for complex These databases are not so good for
queries complex queries
Column-based
Column-oriented databases work on columns and are based on BigTable paper by Google.
Every column is treated separately. Values of single column databases are stored
contiguously.
Column-based NoSQL databases are widely used to manage data warehouses, business
intelligence, CRM, Library card catalogs.
Document-Oriented
Document-Oriented NoSQL DB stores and retrieves data as a key value pair but the value
part is stored as a document. The document is stored in JSON or XML formats. The value is
understood by the DB and can be queried
The document type is mostly used for CMS systems, blogging platforms, real-time analytics
& e-commerce applications. It should not use for complex transactions which require
multiple operations or queries against varying aggregate structures.
Graph-Based
A graph type database stores entities as well the relations amongst those entities. The entity is
stored as a node with the relationship as edges. An edge gives a relationship between nodes.
Every node and edge has a unique identifier.
Graph base database mostly used for social networks, logistics, spatial data .
Relational Database Management System(RDBMS) is not the correct choice when it comes to
handling big data by the virtue of their design since they are not horizontally scalable. If the
database runs on a single server, then it will reach a scaling limit. NoSQL databases are more
scalable and provide superior performance. MongoDB is such a NoSQL database that scales by
adding more and more servers and increases productivity with its flexible document model.
MongoDB Advantages
MongoDB is schema less. It is a document database in which one collection holds
different documents.
There may be difference between number of fields, content and size of the
document from one to other.
Structure of a single object is clear in MongoDB.
There are no complex joins in MongoDB.
MongoDB provides the facility of deep query because it supports a powerful dynamic
query on documents.
It is very easy to scale.
It uses internal memory for storing working sets and this is the reason of its fast
access.
Data Description
Types
String String is the most commonly used datatype. It is used to store data. A string must
be UTF 8 valid in mongodb.
Integer Integer is used to store the numeric value. It can be 32 bit or 64 bit depending on
the server you are using.
Boolean This datatype is used to store boolean values. It just shows YES/NO values.
Min/Max This datatype compare a value against the lowest and highest bson elements.
Keys
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. It makes you
possible to specify your own date time by creating object of date and pass the
value of date, month, year into it.
It may be look like a weird concept, if you are from traditional SQL background where you
need to create a database, table and insert values in the table manually.
Here, in MongoDB you don't need to create a database manually because MongoDB will
create it automatically when you save the value into the defined collection at first time.
You also don't need to mention what you want to create, it will be automatically created at
the time you save the value into the defined collection.
Syntax:
use DATABASE_NAME
If the database already exists, it will return the existing database.
For example, we are going to create database studentdb using user interface in MongoDB.
Now to do this things using command line, click the arrow button given below on
the screen. Command line screen will appear. Type the following command.
Syntax:
db.createCollection(name, options)
Here,
Options: is a document type, specifies the memory size and indexing of the collection. It is
an optional parameter.
During the creation of database studentdb, we have created a collection named as sem1. This
creation is done using user interface. Now we will create collection name as sem2. Type the
following command into command window,
Use studentdb
Db.createcollection(“sem2”)
The db.collection.drop() method does not take any argument and produce an error when it is
called with an argument. This method removes all the indexes associated with the dropped
collection.
Syntax:
db.COLLECTION_NAME.drop()
use the database from which you want to remove the collection. Follow these commands.
The drop Database command is used to drop a database. It also deletes the associated data
files. It operates on the current database.
Syntax:
db.dropDatabase()
This syntax will delete the selected database. In the case you have not selected any database,
it will delete default "test" database. See the following screenshot.
List of databases are display on the screen. Now we want to remove studentdb database from
the list. First check that how many collections are there in studentdb. Then remove the
database. Consider following commands to perform the deletion of database.
Command:
The MongoDB query operator includes comparison, logical, element, evaluation, Geospatial,
array, bitwise, and comment operators.
$eq
The $eq specifies the equality condition. It matches documents where the value of a field
equals the specified value.
Syntax:
Example:
The above example queries the toys collection to select all documents where the value of the
price filed equals 300.
$gt
The $gt chooses a document where the value of the field is greater than the specified value.
Syntax:
Example:
$gte
The $gte choose the documents where the field value is greater than or equal to a specified
value.
Prepared By: Assit.Prof.Hiral Joshi
Dr. Megha D. Rana Page 16
Unit – 1 Concept of NoSQL : MongoDB
Syntax
Example:
$in
The $in operator choose the documents where the value of a field equals any value in the
specified array.
Syntax:
Example:
$lt
The $lt operator chooses the documents where the value of the field is less than the specified
value.
Syntax:
Example:
$lte
The $lte operator chooses the documents where the field value is less than or equal to a
specified value.
Syntax:
Example:
$ne
The $ne operator chooses the documents where the field value is not equal to the specified
value.
Syntax:
Example:
$nin
The $nin operator chooses the documents where the field value is not in the specified array or
does not exist.
Syntax:
Example:
$and
The $and operator works as a logical AND operation on an array. The array should be of one
or more expressions and chooses the documents that satisfy all the expressions in the array.
Syntax:
Example:
$not
Prepared By: Assit.Prof.Hiral Joshi
Dr. Megha D. Rana Page 18
Unit – 1 Concept of NoSQL : MongoDB
The $not operator works as a logical NOT on the specified expression and chooses the
documents that are not related to the expression.
Syntax:
Example:
$nor
The $nor operator works as logical NOR on an array of one or more query expression and
chooses the documents that fail all the query expression in the array.
Syntax:
Example:
$or
It works as a logical OR operation on an array of two or more expressions and chooses
documents that meet the expectation at least one of the expressions.
Syntax:
Example:
$exists
The exists operator matches the documents that contain the field when Boolean is true. It also
matches the document where the field value is null.
Syntax:
Example:
$type
The type operator chooses documents where the value of the field is an instance of the
specified BSON type.
Syntax:
Example:
$expr
The expr operator allows the use of aggregation expressions within the query language.
Syntax:
{ $expr: { <expression> } }
Example:
$jsonSchema
Syntax:
$mod
The mod operator selects the document where the value of a field is divided by a divisor has
the specified remainder.
Syntax:
Example:
$regex
It provides regular expression abilities for pattern matching strings in queries. The MongoDB
uses regular expressions that are compatible with Perl.
Syntax:
{ <field>: /pattern/<options> }
Example:
$text
The $text operator searches a text on the content of the field, indexed with a text index.
Syntax:
{
$text:
{
$search: <string>,
$language: <string>,
$caseSensitive: <boolean>,
$diacriticSensitive: <boolean>
}
}
Example:
$where
The "where" operator is used for passing either a string containing a JavaScript expression or
a full JavaScript function to the query system.
Example:
$geoIntersects
It selects only those documents whose geospatial data intersects with the given GeoJSON
object.
Syntax:
{
<location field>: {
$geoIntersects: {
$geometry: {
type: "<object type>" ,
coordinates: [ <coordinates> ]
}
}
}
}
Example:
db.places.find(
{
loc: {
$geoIntersects: {
$geometry: {
type: "Triangle" ,
coordinates: [
[ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ] ]
]
}
}
}
}
$geoWithin
The geoWithin operator chooses the document with geospatial data that exists entirely within
a specified shape.
Syntax:
{
<location field>: {
$geoWithin: {
$geometry: {
type: <"Triangle" or "Rectangle"> ,
coordinates: [ <coordinates> ]
}
}
}
$near
The near operator defines a point for which a geospatial query returns the documents from
close to far.
Syntax:
{
<location field>: {
$near: {
$geometry: {
type: "Point" ,
coordinates: [ <longitude> , <latitude> ]
},
Example:
db.places.find(
{
location:
{ $near :
{
$geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
$minDistance: 1000,
$maxDistance: 5000
}
}
}
$nearSphere
The nearsphere operator specifies a point for which the geospatial query returns the document
from nearest to farthest.
Syntax:
{
$nearSphere: [ <x>, <y> ],
$minDistance: <distance in radians>,
$maxDistance: <distance in radians>
}
Example:
db.legacyPlaces.find(
{ location : { $nearSphere : [ -73.9667, 40.78 ], $maxDistance: 0.10 } }
)
$all
It chooses the document where the value of a field is an array that contains all the specified
elements.
Syntax:
Example:
$elemMatch
The operator relates documents that contain an array field with at least one element that
matches with all the given query criteria.
Syntax:
Example:
db.books.find(
{ results: { $elemMatch: { $gte: 500, $lt: 400 } } }
)
$size
It selects any array with the number of the element specified by the argument.
Syntax:
$bitsAllClear
It matches the documents where all the bit positions given by the query are clear infield.
Syntax:
Example:
db.inventory.find( { a: { $bitsAllClear: [ 1, 5 ] } } )
$bitsAllSet
The bitallset operator matches the documents where all the bit positions given by the query
are set in the field.
Syntax:
Example:
db.inventory.find( { a: { $bitsAllClear: [ 1, 5 ] } } )
$bitsAnyClear
The bitAnyClear operator matches the document where any bit of positions given by the
query is clear in the field.
Syntax:
Example:
db.inventory.find( { a: { $bitsAnyClear: [ 5, 10 ] } } )
$bitsAnySet
It matches the document where any of the bit positions given by the query are set in the field.
Syntax:
Example:
db.inventory.find( { a: { $bitsAnySet: [ 1, 5 ] } } )
$comment
The $comment operator associates a comment to any expression taking a query predicate.
Syntax:
Example:
db.inventory.find(
{
x: { $mod: [ 1, 0 ] },
$comment: "Find Odd values."
}
The $ operator limits the contents of an array from the query results to contain only the first
element matching the query document.
Syntax:
$elemMatch
The content of the array field made limited using this operator from the query result to
contain only the first element matching the element $elemMatch condition.
Syntax:
$meta
The meta operator returns the result for each matching document where the metadata
associated with the query.
Syntax:
{ $meta: <metaDataKeyword> }
Example:
db.books.find(
Prepared By: Assit.Prof.Hiral Joshi
Dr. Megha D. Rana Page 27
Unit – 1 Concept of NoSQL : MongoDB
<query>,
{ score: { $meta: "textScore" } }
$slice
Syntax:
Example:
1. {
2. <operator1>: { <field1>: <value1>, ... },
3. <operator2>: { <field2>: <value2>, ... },
4. }
Field Operator
$currentDate
It updates the elements of a field to the current date, either as a Date or a timestamp. The
default data type of this operator is the date.
Syntax:
Example:
1. db.books.insertOne(
$inc
Syntax:
Example:
1. {
2. _id: 000438,
3. sku: "MongoDB",
4. quantity: 1,
5. metrics: {
6. orders: 2,
7. ratings: 3.5
8. }
9. }
$min
It changes the value of the field to a specified value if the specified value is less than the
current value of the filed.
Syntax:
Example:
$max
It changes the value of the field to a specified value if the specified value is greater than the
current value of the filed.
Syntax:
Example:
$mul
Syntax:
Example:
1. db.books.update(
2. { _id: 1 },
3. { $mul: { price: NumberDecimal("180.25"), qty: 2 } }
4. )
$rename
Syntax:
Example:
$set
The set operator changes the value of a field with the specified value.
Syntax:
Example:
1. {
2. _id: 100,
3. sku: "abc123",
4. quantity: 50,
5. instock: true,
6. reorder: false,
7. details: { model: "14Q2", make: "xyz" },
8. tags: [ "technical", "non technical" ],
9. ratings: [ { by: "ijk", rating: 4 } ]
$setOnInsert
If the upsert is set to true, then it results in an insert of a document, then setOnInsert operator
assigns the specified values to the field in the document.
Syntax:
1. db.collection.update(
2. <query>,
3. { $setOnInsert: { <field1>: <value1>, ... } },
4. { upsert: true }
5. )
$unset
Syntax:
Example:
1. db.products.update(
2. { sku: "unknown" },
3. { $unset: { quantity: "", instock: "" } }
Array Operators
We can update an element in an array without explicitly specifying the position of the
element.
Syntax:
1. { "<array>.$" : value }
Example:
1. db.collection.update(
2. { <array>: value ... },
3. { <update operator>: { "<array>.$" : value } }
$[ ]
The positional operator indicates that the update operator should change all the elements in
the given array field.
Syntax:
Example:
1. db.collection.updateMany(
2. { <query conditions> },
3. { <update operator>: { "<array>.$[]" : value } }
$[<identifier>]
Syntax:
Example:
$addToSet
It adds an element to an array unless the element is already present, in which case this
operator does nothing to that array.
Syntax:
Example:
1. db.books.update(
2. { _id: 1 },
3. { $addToSet: { tags: "MongoDB" } }
$pop
We can remove the first or last element of an array using the pop operator. We need to pass
the value of pop as -1 to remove the first element of an array and 1 to remove the last element
in an array.
Syntax:
Example:
$pull
Using a pull operator, we can remove all the instances of a value in an array that matches the
specified condition.
Syntax:
Example:
$push
Syntax:
Example:
$pullAll
We can remove all instances of the specified value from an existing array using the pullAll
operator. It removes elements that match the listed value.
Syntax:
Example:
Modifiers
$each
It is used with the $addToSet operator and the $push operator. It is used with the addToSet
operator to add multiple values to an array if the value does not exist in the field.
Syntax:
Syntax:
Example:
$position
It specifies the location where the push operator inserts elements inside an array.
Syntax:
1. {
2. $push: {
3. <field>: {
4. $each: [ <value1>, <value2>, ... ],
5. $position: <num>
6. }
7. }
Example:
1. db.students.update(
2. { _id: 1 },
3. {
4. $push: {
5. scores: {
6. $each: [ 50, 60, 70 ],
7. $position: 0
8. }
9. }
10. }
11. )
$slice
This modifier is used to limit the number of array elements during the push operation.
Syntax:
1. {
2. $push: {
3. <field>: {
4. $each: [ <value1>, <value2>, ... ],
5. $slice: <num>
6. }
7. }
Example:
1. db.students.update(
2. { _id: 1 },
3. {
4. $push: {
5. scores: {
6. $each: [ 80, 78, 86 ],
7. $slice: -5
8. }
9. }
10. }
11. )
$sort
The sort modifier arranges the values of an array during the push operation.
Syntax:
Prepared By: Assit.Prof.Hiral Joshi
Dr. Megha D. Rana Page 36
Unit – 1 Concept of NoSQL : MongoDB
1. {
2. $push: {
3. <field>: {
4. $each: [ <value1>, <value2>, ... ],
5. $sort: <sort specification>
6. }
7. }
Example:
1. db.students.update(
2. { _id: 1 },
3. {
4. $push: {
5. quizzes: {
6. $each: [ { id: 3, score: 8 }, { id: 4, score: 7 }, { id: 5, score: 6 } ],
7. $sort: { score: 1 }
8. }
9. }
10. }
11. )
Bitwise Operator
$bit
The bit operator updates a field using a bitwise operation. It supports bitwise AND, bitwise
OR, and bitwise XOR operations.
Syntax:
Example:
$abs
Syntax:
1. { $abs: <number> }
Example:
1. db.score.aggregate([
2. {
3. $school: { marks: { $abs: { $subtract: [ "$max", "$min" ] } } }
4. }
5. ])
$add
It adds two or more numbers and a date. If one of the arguments is a date, then the date treats
the other argument as milliseconds to add to the date.
Syntax:
Example:
1. db.books.aggregate(
2. [
3. { $project: { item: 1, total: { $add: [ "$price", "$tax" ] } } }
4. ]
5. )
Prepared By: Assit.Prof.Hiral Joshi
Dr. Megha D. Rana Page 38
Unit – 1 Concept of NoSQL : MongoDB
$ceil
The ceil operator returns the smallest integer that is greater than or equal to the specified
number.
Syntax:
1. { $ceil: <number> }
Example:
$divide
Syntax:
Example:
$exp
The exp operator is used to raise Euler's number to the specified exponent and returns the
result.
Syntax:
1. { $exp: <exponent> }
Example:
$floor
The floor operator returns the greatest integer less than or equal to the specified number.
Syntax:
1. { $floor: <number> }
Example:
$ln
The ln operator calculates the natural logarithm of a number and returns the result as a
double.
Syntax:
1. { $ln: <number> }
Example:
$log
The log operator calculates the log of a number for the specified base and returns the result as
double.
Syntax:
Example:
1. db.examples.aggregate([
2. { $project: { bitsNeeded:
3. {
4. $floor: { $add: [ 1, { $log: [ "$positiveInt", 2 ] } ] } } }
5. }
6. ])
$log10
The log10 operator calculates the log base 10 of a number and returns the result as a double.
Syntax:
1. { $log10: <number> }
Example:
$mod
The mod operator divides one number with another and returns the remainder.
Syntax:
Example:
1. db.planning.aggregate(
2. [
3. { $project: { remainder: { $mod: [ "$hours", "$tasks" ] } } }
4. ]
5. )
$multi0ply
Syntax:
Example:
$pow
The pow operator raises the number to the given exponent and returns the result.
Syntax:
Example:
$round
The round operator rounds a number to a whole integer or a specified decimal place.
Syntax:
Example:
$sqrt
The sqrt operator returns the square root of a positive number as double.
Syntax:
1. { $sqrt: <number> }
Example:
1. db.points.aggregate([
2. {
3. $project: {
4. distance: {
5. $sqrt: {
6. $add: [
7. { $pow: [ { $subtract: [ "$p2.y", "$p1.y" ] }, 2 ] },
8. { $pow: [ { $subtract: [ "$p2.x", "$p1.x" ] }, 2 ] }
9. ]
10. }
11. }
12. }
13. }
14. ])
$subtract
The subtract operator subtracts two or more numbers to return the difference of the number.
Syntax:
Example:
$trunc
The trunc command deletes the data from the specified decimal place.
Syntax:
Example:
$arrayElemAt
Syntax:
Example:
1. db.users.aggregate([
2. {
3. $project:
4. {
5. name: 1,
6. first: { $arrayElemAt: [ "$favorites", 0 ] },
7. last: { $arrayElemAt: [ "$favorites", -1 ] }
8. }
9. }
10. ])
$arrayToObject
Syntax:
Example:
1. db.inventory.aggregate(
2. [
3. {
4. $project: {
5. item: 1,
6. dimensions: { $arrayToObject: "$dimensions" }
7. }
8. }
9. ]
10. )
$concatArrays
The concatArrays operator joins the array to return the concatenated array.
Syntax:
Example:
1. db.warehouses.aggregate([
2. { $project: { items: { $concatArrays: [ "$instock", "$ordered" ] } } }
3. ])
$filter
The filter operator selects a subset of an array to return the result based on the specified
condition.
Syntax:
Example:
1. db.sales.aggregate([
2. {
3. $project: {
4. items: {
5. $filter: {
6. input: "$items",
7. as: "item",
8. cond: { $gte: [ "$$item.price", 100 ] }
9. }
10. }
11. }
12. }
13. ])
$in
The in operator returns a boolean indicating that the specified value is in the array or not.
Syntax:
Example:
1. db.fruit.aggregate([
2. {
3. $project: {
4. "store location" : "$location",
5. "has bananas" : {
6. $in: [ "bananas", "$in_stock" ]
7. }
8. }
9. }
10. ])
$indexOfArray
The indexOfArray operator searches the array for the occurrence of a specified value and
returns the array index of the first occurrence.
Syntax:
Example:
1. db.inventory.aggregate(
2. [
3. {
4. $project:
5. {
6. index: { $indexOfArray: [ "$items", 2 ] },
7. }
8. }
9. ]
10. )
$isArray
Syntax:
1. { $isArray: [ <expression> ] }
Example:
$map
The map operator attaches value to each item in an array and returns an array with the applied
result.
Syntax:
Example:
1. db.grades.aggregate(
2. [
3. { $project:
4. { adjustedGrades:
5. {
6. $map:
7. {
8. input: "$quizzes",
9. as: "grade",
10. in: { $add: [ "$$grade", 2 ] }
11. }
12. }
13. }
14. }
15. ]
16. }
$objectToArray
Syntax:
1. { $objectToArray: <object> }
Example:
1. db.inventory.aggregate(
2. [
3. {
4. $project: {
5. item: 1,
6. dimensions: { $objectToArray: "$dimensions" }
7. }
8. }
9. ]
10. )
$range
The range operator returns an array whose elements are a generated sequence of numbers.
Syntax:
Example:
1. db.distances.aggregate([{
2. $project: {
3. _id: 0,
4. city: 1,
5. "Rest stops": { $range: [ 0, "$distance", 25 ] } } } ] )
$reduce
The reduce operator applies an expression to each element in an array and combines them
into a single value.
Syntax:
1. {
2. $reduce: {
3. input: <array>,
4. initialValue: <expression>,
5. in: <expression>
6. }
7. }
Example:
$reverseArray
Syntax:
Example:
$size
The size operator counts and returns the total number of items in an array.
Syntax:
1. { $size: <expression> }
Example:
$slice
Syntax:
Example:
$zip
The zip operator transposes an array so that the first element of the output array would be an
array containing the first element of the first input array.
Syntax:
1. {
2. $zip: { inputs: [ <array expression1>, ... ], useLongestLength: <boolean>, defaults: <array
expression> } }
Example:
In MongoDB, limit() method is used to limit the fields of document that you want to show.
Sometimes, you have a lot of fields in collection of your database and have to retrieve only 1
or 2. In such case, limit() method is used.
Syntax:
1. db.COLLECTION_NAME.find().limit(NUMBER)
1. [
2. {
3. Course: "Java",
4. details: { Duration: "6 months", Trainer: "Sonoo Jaiswal" },
5. Batch: [ { size: "Medium", qty: 25 } ],
6. category: "Programming Language"
7. },
8. {
9. Course: ".Net",
10. details: { Duration: "6 months", Trainer: "Prashant Verma" },
11. Batch: [ { size: "Small", qty: 5 }, { size: "Medium", qty: 10 }, ],
12. category: "Programming Language"
13. },
14. {
15. Course: "Web Designing",
16. details: { Duration: "3 months", Trainer: "Rashmi Desai" },
17. Batch: [ { size: "Small", qty: 5 }, { size: "Large", qty: 10 } ],
18. category: "Programming Language"
19. }
20. ];
Here, you have to display only one field by using limit() method.
Example
1. db.javatpoint.find().limit(1)
Output:
Output:
Syntax
1. db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
Scenario:
Consider here also the above discussed example. The collection javatpoint has three
documents.
1. [
2. {
3. Course: "Java",
4. details: { Duration: "6 months", Trainer: "Sonoo Jaiswal" },
5. Batch: [ { size: "Medium", qty: 25 } ],
6. category: "Programming Language"
7. },
8. {
9. Course: ".Net",
10. details: { Duration: "6 months", Trainer: "Prashant Verma" },
11. Batch: [ { size: "Small", qty: 5 }, { size: "Medium", qty: 10 }, ],
12. category: "Programming Language"
13. },
14. {
15. Course: "Web Designing",
Execute the following query to retrieve only one document and skip 2 documents.
Example
1. db.javatpoint.find().limit(1).skip(2)
Output:
As you can see, the skip() method has skipped first and second documents and shows only
third document.
Syntax:
1. db.COLLECTION_NAME.find().sort({KEY:1})
1. [
2. {
3. Course: "Java",
4. details: { Duration: "6 months", Trainer: "Sonoo Jaiswal" },
5. Batch: [ { size: "Medium", qty: 25 } ],
6. category: "Programming Language"
7. },
8. {
9. Course: ".Net",
10. details: { Duration: "6 months", Trainer: "Prashant Verma" },
11. Batch: [ { size: "Small", qty: 5 }, { size: "Medium", qty: 10 }, ],
12. category: "Programming Language"
13. },
14. {
15. Course: "Web Designing",
16. details: { Duration: "3 months", Trainer: "Rashmi Desai" },
17. Batch: [ { size: "Small", qty: 5 }, { size: "Large", qty: 10 } ],
18. category: "Programming Language"
19. }
20. ];
1. db.javatpoint.find().sort({"Course":-1})
Query Modifiers
We have number of meta operation in addition to the MongoDB Query Operators to modify
the output or behaviour of a query.
Modifiers
$comment
The comment operator makes it possible to add a comment to a query in any context.
Syntax:
$explain
The explain modifier provides details about the query plan. It returns a file that describes the
process and indexes used to return the query. It may give useful insight when attempting to
optimize a query.
Syntax:
$hint
This operator is deprecated in the mongo shell now. The hint operator attaches the optimizer
to use the declared index to fulfill the query. It is also used for testing query performance and
indexing strategies.
Syntax:
1. db.users.find().hint( { age: 1 } )
Prepared By: Assit.Prof.Hiral Joshi
Dr. Megha D. Rana Page 55
Unit – 1 Concept of NoSQL : MongoDB
$max
The max operator is deprecated in mongo shell since v3.2. It defines a max value to specify
the exclusive upper bound for the given index in order to limit the results of find ().
Syntax:
1. db.example.find( { <query> } ).max( { field1: <max value>, ... fieldN: <max valueN> } )
$maxTimeMS
It is also deprecated since v3.2. It defines a cumulative time in ms for processing operations
on the cursor.
Syntax:
1. db.collection.find().maxTimeMS(100)
$min
The min operator is used to find a minimum value to declare the included lower bound for a
specified index to constrain the results of find ().
Syntax:
1. db.collection.find( { <query> } ).min( { field1: <min value>, ... fieldN: <min valueN>} )
$orderby
The orderby operator arranges the results of a query in ascending or descending order.
Syntax:
1. db.collection.find().sort( { age: -1 } )
$query
Syntax:
$returnKey
Prepared By: Assit.Prof.Hiral Joshi
Dr. Megha D. Rana Page 56
Unit – 1 Concept of NoSQL : MongoDB
The return key returns the index fields for the results of the query. If returnkey operator is set
to true then the returned documents will not contain any fields.
Syntax:
$showDiskLoc
The showDiskLoc operator adds a field to the resultant documents. The value of the added
diskLoc field is a document that contains the disk location details.
Syntax:
1. "$diskLoc": {
2. "file": <int>,
3. "offset": <int>
$natural
The natural operator is a special sort order operator that arranges the documents using the
order of documents on disk using the cursor.hint ().
CRUD: Documents
MongoDB insert documents
In MongoDB, the db.collection.insert() method is used to add or insert new documents into
a collection in your database.
Upsert
Upsert is an operation that performs either an update of existing document or an insert of new
document if the document to modify does not exist.
Syntax
1. >db.COLLECTION_NAME.insert(document)
Let?s take an example to demonstrate how to insert a document into a collection. Create a
database named studentdb. In this example we insert a document into a collection named
coursedetail. (Method for creation of database and collection is given in beginning of this
unit.) This operation will automatically create a collection if the collection does not currently
exist.
Example
1. db. coursedetail.insert(
2. {
3. course: "java",
4. details: {
5. duration: "6 months",
6. Trainer: "Sonoo jaiswal"
7. },
8. Batch: [ { size: "Small", qty: 15 }, { size: "Medium", qty: 25 } ],
9. category: "Programming language"
10. }
11. )
After the successful insertion of the document, the operation will return a WriteResult object
with its status.
Output:
WriteResult({ "nInserted" : 1 })
Here the nInserted field specifies the number of documents inserted. If an error is occurred
then the WriteResult will specify the error information.
If the insertion is successful, you can view the inserted document by the following query.
1. >db. coursedetail.find()
Output:
Note: Here, the ObjectId value is generated by MongoDB itself. It may differ from the one
shown.
1. var Allcourses =
2. [
3. {
4. Course: "Java",
5. details: { Duration: "6 months", Trainer: "Sonoo Jaiswal" },
6. Batch: [ { size: "Medium", qty: 25 } ],
7. category: "Programming Language"
8. },
9. {
10. Course: ".Net",
11. details: { Duration: "6 months", Trainer: "Prashant Verma" },
12. Batch: [ { size: "Small", qty: 5 }, { size: "Medium", qty: 10 }, ],
13. category: "Programming Language"
14. },
15. {
16. Course: "Web Designing",
17. details: { Duration: "3 months", Trainer: "Rashmi Desai" },
18. Batch: [ { size: "Small", qty: 5 }, { size: "Large", qty: 10 } ],
19. category: "Programming Language"
20. }
21. ];
Pass this Allcourses array to the db.collection.insert() method to perform a bulk insert.
Note: Here the nInserted field specifies the number of documents inserted. In the case of any
error during the operation, the BulkWriteResult will specify that error.
You can check the inserted documents by using the following query:
1. >db. coursedetail.find()
In its latest version of MongoDB (MongoDB 2.6) provides a Bulk() API that can be used to
perform multiple write operations in bulk.
You should follow these steps to insert a group of documents into a MongoDB collection.
This operation returns an unorder operations builder which maintains a list of operations to
perform .
1. bulk.insert(
2. {
3. course: "java",
4. details: {
Call the execute() method on the bulk object to execute the operations in the list.
1. bulk.execute();
After the successful insertion of the documents, this method will return
a BulkWriteResult object with its status.
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 1,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
Here the nInserted field specifies the number of documents inserted. In the case of any error
during the operation, the BulkWriteResult will specify that error.
Syntax:
1. db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
Example
Consider an example which has a collection name javatpoint. Insert the following documents
in collection:
1. db. coursedetail.insert(
2. {
3. course: "java",
4. details: {
5. duration: "6 months",
6. Trainer: "Sonoo jaiswal"
7. },
8. Batch: [ { size: "Small", qty: 15 }, { size: "Medium", qty: 25 } ],
9. category: "Programming language"
10. }
11. )
1. >db. coursedetail.find()
Output:
1. >db. coursedetail.update({'course':'java'},{$set:{'course':'android'}})
1. >db. coursedetail.find()
Output:
1. Deletion criteria: With the use of its syntax you can remove the documents from the
collection.
Syntax:
1. db.collection_name.remove (DELETION_CRITERIA)
Let's take an example to demonstrate the remove() method. In this example, we remove all
documents from the "javatpoint" collection.
1. db. coursedetail.remove({})
If you want to remove a document that match a specific condition, call the remove() method
with the <query> parameter.
The following example will remove all documents from the javatpoint collection where the
type field is equal to programming language.
The following example will remove a single document from the javatpoint collection where
the type field is equal to programming language.
Summary :
Database
Prepared By: Assit.Prof.Hiral Joshi
Dr. Megha D. Rana Page 63
Unit – 1 Concept of NoSQL : MongoDB
Collections
- Collections do NOT enforce any schema, No join concept.
- We can join multiple collections using Aggregation.
- It’s a set of documents
- Can have any number of document
- Documents can have any dynamic schema. They can be same or different.
Documents
- Is a simple key value pair data
- MongoDB valid document example
- Schema can be different for different documents
- Document can have any data type- as long as it is valid MongoDB data
type
- User defined schema in MongoDB and they are NOT static or Fixed.
- MongoDB will add a key automatically for each document called “_id”.
{
“_id” : “<unique_value>”,
“firstname” : ”Vivekanand College”,
“Lastname” : “For BCA”,
“Email” : “vivekanandbca@gmail.com”
}, /* document1*/
{
“_id” : “<unique_value>”,
“firstname” : ”Vivekanand College”,
“Lastname” : “For BCA”,
“Email” : “vivekanandbca@gmail.com”,
“Address” : “Jahangirpura,surat”
} /*document2*/