UNIT 1 MongoDB Fully Complete
UNIT 1 MongoDB Fully Complete
Features of NoSQL
1. 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, ACIDs
2. 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
3. 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
4. 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.
NoSQL is Shared Nothing.
Advantages of NoSQL
supports query language.
provides fast performance.
provides horizontal scalability.
Can be used as Primary or Analytic Data Source
Big Data Capability
Dis-Advantages 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
Introduction of MongoDb
What is MongoDB?
String − This is the most commonly used datatype to store the data. String in
MongoDB must be UTF-8 valid.
Integer − This type is used to store a numerical value. Integer can be 32 bit or
64 bit depending upon your server.
Boolean − This type is used to store a boolean (true/ false) value.
Double − This type is used to store floating point values.
Min/ Max keys − This type is used to compare a value against the lowest and
highest BSON elements.
Arrays − This type is used to store arrays or list or multiple values into one key.
Timestamp − timestamp. This can be handy for recording when a document
has been modified or added.
Object − This datatype is used for embedded documents.
Null − This type is used to store a Null value.
Symbol − This datatype is used identically to a string; however, it's generally
reserved for languages that use a specific symbol type.
Date − This datatype is used to store the current date or time in UNIX time
format. You can specify your own date time by creating object of Date and
passing day, month, year into it.
Object ID − This datatype is used to store the document’s ID.
Binary data − This datatype is used to store binary data.
Code − This datatype is used to store JavaScript code into the document.
Regular expression − This datatype is used to store regular expression.
Database
Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A
collection exists within a single database. Collections do not enforce a schema.
Documents within a collection can have different fields. Typically, all documents in a
collection are of similar or related purpose.
Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic
schema means that documents in the same collection do not need to have the same set
of fields or structure, and common fields in a collection's documents may hold different
types of data.
The following table shows the relationship of RDBMS terminology with MongoDB.
RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
column Field
mysqld/Oracle mongod
mysql/sqlplus mongo
Sample Document
Following example shows the document structure of a blog site, which is simply a comma
separated key value pair.
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2011,1,20,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2011,1,25,7,45),
like: 5
}
]
}
_id is a 12 bytes hexadecimal number which assures the uniqueness of every document.
You can provide _id while inserting the document. If you don’t provide then MongoDB
provides a unique id for every document. These 12 bytes first 4 bytes for the current
timestamp, next 3 bytes for machine id, next 2 bytes for process id of MongoDB server
and remaining 3 bytes are simple incremental VALUE.
Any relational database has a typical schema design that shows number of tables and the
relationship between these tables. While in MongoDB, there is no concept of relationship.
Enter the required details, select the Server tab, in it you can choose the version of
MongoDB, operating system and, packaging as:
Now install the downloaded file, by default, it will be installed in the folder C:\Program
Files\.
MongoDB requires a data folder to store its files. The default location for the MongoDB
data directory is c:\data\db. So you need to create this folder using the Command Prompt.
Execute the following command sequence.
C:\>md data
C:\md data\db
Then you need to specify set the dbpath to the created directory in mongod.exe. For the
same, issue the following commands.
In the command prompt, navigate to the bin directory current in the MongoDB
installation folder. Suppose my installation folder is C:\Program Files\MongoDB
C:\Users\XYZ>d:cd C:\Program Files\MongoDB\Server\4.2\bin
C:\Program Files\MongoDB\Server\4.2\bin>mongod.exe --dbpath "C:\data"
This will show waiting for connections message on the console output, which indicates
that the mongod.exe process is running successfully.
Now to run the MongoDB, you need to open another command prompt and issue the
following command.
Start MongoDB
sudo service mongodb start
Stop MongoDB
sudo service mongodb stop
Restart MongoDB
sudo service mongodb restart
To use MongoDB run the following command.
mongo
This will connect you to running MongoDB instance.
MongoDB Help
To get a list of commands, type db.help() in MongoDB client. This will give you a list of
commands as shown in the following screenshot.
MongoDB Statistics
To get stats about MongoDB server, type the command db.stats() in MongoDB client.
This will show the database name, number of collection and documents in the database.
Output of the command is shown in the following screenshot.
{
_id: ,
Emp_ID: "10025AE336"
Personal_details:{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26"
},
Contact: {
e-mail: "[email protected]",
phone: "9848022338"
},
Address: {
city: "Hyderabad",
Area: "Madapur",
State: "Telangana"
}
}
Employee:
{
_id: <ObjectId101>,
Emp_ID: "10025AE336"
}
Personal_details:
{
_id: <ObjectId102>,
empDocID: " ObjectId101",
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26"
}
Contact:
{
_id: <ObjectId103>,
empDocID: " ObjectId101",
e-mail: "[email protected]",
phone: "9848022338"
}
Address:
{
_id: <ObjectId104>,
empDocID: " ObjectId101",
city: "Hyderabad",
Area: "Madapur",
State: "Telangana"
}
Duplicate the data (but limited) because disk space is cheap as compare to compute
time.
Do joins while write, not on read.
Optimize your schema for most frequent use cases.
Do complex aggregation in the schema.
Example
Suppose a client needs a database design for his blog/website and see the differences
between RDBMS and MongoDB schema design. Website has the following requirements.
While in MongoDB schema, design will have one collection post and the following
structure −
{
_id: POST_ID
title: TITLE_OF_POST,
description: POST_DESCRIPTION,
by: POST_BY,
url: URL_OF_POST,
tags: [TAG1, TAG2, TAG3],
likes: TOTAL_LIKES,
comments: [
{
user:'COMMENT_BY',
message: TEXT,
dateCreated: DATE_TIME,
like: LIKES
},
{
user:'COMMENT_BY',
message: TEXT,
dateCreated: DATE_TIME,
like: LIKES
}
]
}
So while showing the data, in RDBMS you need to join three tables and in MongoDB, data
will be shown from one collection only.
Syntax
use DATABASE_NAME
Example
If you want to use a database with name <mydb>, then use DATABASE statement
would be as follows –
>use mydb
switched to db mydb
To check the currently selected database, use the command db
>db
mydb
To check your databases list, use the command show dbs.
>show dbs
local 40.00KiB
admin 40.00KiB
config 60.00KiB
Dropping database
The dropDatabase() Method
MongoDB db.dropDatabase() command is used to drop a existing database.
Syntax
db. dropDatabase()
This will delete the selected database. If you have not selected any database, then it will
delete default 'test' database.
Example
First, check the list of available databases by using the command, show dbs.
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>
If you want to delete new database <mydb>, then dropDatabase() command would be
as follows −
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>
Now check list of databases.
>show dbs
local 0.78125GB
test 0.23012GB
>
Syntax
db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and
is used to specify configuration of collection.
Options parameter is optional, so you need to specify only the name of the collection.
Following is the list of options you can use −
While inserting the document, MongoDB first checks size field of capped collection, then
it checks max field.
Examples
Basic syntax of createCollection() method without options is as follows −
>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>
To check the created collection, use the command show collections.
>show collections
Mycollection
If you want to see the inserted document, use the find() command.
Syntax
db.collection_name.find()
Drop collections
In MongoDB, db.collection.drop() method is used to drop a collection from a database.
It completely removes a collection from the database and does not leave any indexes
associated with the dropped collections.
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()
Example
>use mydb
switched to db mydb
>show collections
mycollection
>db.mycollection.drop()
true
>show collections
drop() method will return true, if the selected collection is dropped successfully, otherwise
it will return false.
MongoDB is use for various things like building an application (including web and
mobile), or analysis of data, or an administrator of a MongoDB database, in all these
cases we need to interact with the MongoDB server to perform certain operations like
entering new data into the application, updating data into the application, deleting
data from the application, and reading the data of the application.
MongoDB provides a set of some basic but most essential operations that will help
you to easily interact with the MongoDB server and these operations are known
as CRUD operations.
Create Operations
The create or insert operations are used to insert or add new documents in the
collection. If a collection does not exist, then it will create a new collection in the
database. You can perform, create operations using following methods provided by
the MongoDB:
>db.COLLECTION_NAME.insert(document)
Example
> db.createCollection("post")
> db.post.insert([
{
title: "MongoDB Overview",
description: "MongoDB is no SQL database",
by: "tutorials point",
url: "http://www.tutorialspoint.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 100
},
{
title: "NoSQL Database",
description: "NoSQL database doesn't have tables",
by: "tutorials point",
url: "http://www.tutorialspoint.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 20,
comments: [
{
user:"user1",
message: "My first comment",
dateCreated: new Date(2013,11,10,2,35),
like: 0
}
]
}
])
>
To insert the document you can use db.post.save(document) also. If you don't
specify _id in the document then save() method will work same as insert() method. If
you specify _id then it will replace whole data of document containing _id as specified in
save() method.
>db.COLLECTION_NAME.insertOne(document)
Example
> db.createCollection("empDetails")
{ "ok" : 1 }
>db.empDetails.insertOne(
{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26",
e_mail: "[email protected]",
phone: "9848022338"
})
Syntax
The basic syntax of insert() command is as follows −
>db.COLLECTION_NAME.insertMany(document)
The insertMany() method
You can insert multiple documents using the insertMany() method. To this method you
need to pass an array of documents.
Example
Following example inserts three different documents into the empDetails collection using
the insertMany() method.
> db.empDetails.insertMany(
[
{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26",
e_mail: "[email protected]",
phone: "9000012345"
},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Date_Of_Birth: "1990-02-16",
e_mail: "[email protected]",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Date_Of_Birth: "1990-02-16",
e_mail: "[email protected]",
phone: "9000054321"
}
]
)
Read Operations
The Read operations are used to retrieve documents from the collection, or in other
words, read operations are used to query a collection for a document. You can
perform read operation using the following method provided by the MongoDB:
The find() Method
To query data from MongoDB collection, you need to use MongoDB's find() method.
Syntax
The basic syntax of find() method is as follows −
>db.COLLECTION_NAME.find()
find() method will display all the documents in a non-structured way.
Example
Assume we have created a collection named mycol as –
> use sampleDB
switched to db sampleDB
> db.createCollection("mycol")
{ "ok" : 1 }
>
And inserted 3 documents in it using the insert() method as shown below –
> db.mycol.insert([
{
title: "MongoDB Overview",
> db.mycol.find()
[
{
_id: ObjectId("64a11722e0de5ab72e1768e7"),
title: 'MongoDB Overview',
description: 'MongoDB is no SQL database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: [ 'mongodb', 'database', 'NoSQL' ],
likes: 100
},
{
_id: ObjectId("64a11722e0de5ab72e1768e8"),
title: 'NoSQL Database',
description: "NoSQL database doesn't have tables",
MS. ESHA PATEL Page 26
Unit-1: concepts of NoSQL: MongoDB
Syntax
>db.COLLECTION_NAME.find().pretty()
The findOne() Method
Apart from the find() method, there is findOne() method, that returns only one
document.
Syntax
>db.COLLECTIONNAME.findOne()
Example
Following example retrieves the document with title MongoDB Overview.
> db.mycol.findOne({title: "MongoDB Overview"})
{
"_id" : ObjectId("5dd6542170fb13eec3963bf0"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no SQL database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : ["mongodb","database","NoSQL"],
"likes" : 100
}
Update Operations
MongoDB's update() and save() methods are used to update document into a
collection. The update() method updates the values in the existing document while the
save() method replaces the existing document with the document passed in save()
method.
You can specify criteria, or filters, that identify the documents to update. These filters
use the same syntax as read operations.
>db.users.deleteMany( collection
{status: “reject”} delete filter
)
Syntax
The basic syntax of update() method is as follows −
>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
Example
Consider the mycol collection has the following data.
Following example will set the new title 'New MongoDB Tutorial' of the documents whose
title is 'MongoDB Overview'.
>db.mycol.save(
{
"_id" : ObjectId("507f191e810c19729de860ea"),
"title":"Tutorials Point New Topic",
"by":"Tutorials Point"
}
)
Syntax
The basic syntax of findOneAndUpdate() method is as follows −
>db.COLLECTION_NAME.findOneAndUpdate(SELECTIOIN_CRITERIA, UPDATED_DATA)
Example
Assume we have created a collection named empDetails and inserted three documents in
it as shown below −
> db.empDetails.insertMany(
[
{
First_Name: "Radhika",
Last_Name: "Sharma",
Age: "26",
e_mail: "[email protected]",
phone: "9000012345"
},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Age: "27",
e_mail: "[email protected]",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Age: "24",
e_mail: "[email protected]",
phone: "9000054321"
}
]
)
Following example updates the age and email values of the document with name
'Radhika'.
> db.empDetails.findOneAndUpdate(
{First_Name: 'Radhika'},
{ $set: { Age: '30',e_mail: '[email protected]'}}
)
{
"_id" : ObjectId("5dd6636870fb13eec3963bf5"),
"First_Name" : "Radhika",
"Last_Name" : "Sharma",
"Age" : "30",
"e_mail" : "[email protected]",
"phone" : "9000012345"
}
>db.empDetails.find() //To show the changes of collection data
>db.COLLECTION_NAME.updateOne(<filter>, <update>)
Example
> db.empDetails.updateOne(
{First_Name: 'Radhika'},
{ $set: { Age: '30',e_mail: '[email protected]'}}
)
MongoDB updateMany() method
The updateMany() method updates all the documents that matches the given filter.
Syntax
The basic syntax of updateMany() method is as follows −
>db.COLLECTION_NAME.update(<filter>, <update>)
Example
> db.empDetails.updateMany(
{Age:{ $gt: "25" }},
{ $set: { Age: '00'}}
)
You can see the updated values if you retrieve the contents of the document using the
find method as shown below –
> db.empDetails.find()
[
{
_id:ObjectId(“64a053784f8fda2b751f5ccf”),
FirstName:’Radhika’,
LastName:’Sharma’
Age:’00’,
e_mail:’radhika123gmail.com’,
phone:’9000012345’,
},
{
_id:ObjectId(“”64a053784f8fda2b751f5cd0”),
FirstName:’Rachel’,
LastName:’Christopher’,
Age:’00’
e_mail:’Rachel_Christopher,[email protected]’,
phone:’9000054321’
},
{
_id:ObjectId(“64a053784f8fda2b751f5cd0”),
FirstName:’Fathima’,
LastName:’Sheik’,
Age:’24’,
e_mail:’Fathima_Sheik.123@gmail,com’,
phone:’9000054321’
}]
Delete Operations
The delete operation are used to delete or remove the documents from a collection.
You can perform delete operations using the following methods provided by the
MongoDB:
You can specify criteria, or filters, that identify the documents to remove. These filters use the
same syntax as read operations.
>db.users.deleteMany( collection
{status: “reject”} delete filter
)
db.collection.deleteOne()
It is used to delete a single document from the collection that satisfy the given criteria.
or
It method removes only the first document matched by the query filter document.
Syntax
Basic syntax of deleteOne() method is as follows −
>db.COLLECTION_NAME.deleteOne (DELLETION_CRITTERIA)
Example
Consider the empd collection has the following data.
[{
_id: ObjectId("649d8341682c1b6a14497710"),
First_Name: 'Rachel',
Last_Name: 'Christopher',
Date_Of_Birth: '1990-02-16',
e_mail: '[email protected]',
phone: '9000054321'
},
{
_id: ObjectId("649d8341682c1b6a14497711"),
First_Name: 'Fathima',
Last_Name: 'Sheik',
Date_Of_Birth: '1990-02-16',
e_mail: '[email protected]',
phone: '9000054321'
}
]
Following example will delete all the documents whose Last_Name is 'Sheik'.
db.collection.deleteMany()
If you don't specify deletion criteria, then MongoDB will delete whole documents from
the collection. This is equivalent of SQL's truncate command.
>db.empd.deleteMany({})
{ acknowledged: true, deletedCount: 1 }
> db.empd.find()
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Example
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
>db.empd.remove({})
{acknowledged: true, deletedCount:2}
>
Syntax
To query documents based on the AND condition, you need to use $and keyword.
Following is the basic syntax of AND −
Following example will show all the tutorials written by 'tutorials point' and whose title is
'MongoDB Overview'.
"NoSQL"
],
"likes" : 100
}
>
For the above given example, equivalent where clause will be ' where by = 'tutorials
point' AND title = 'MongoDB Overview' '. You can pass any number of key, value pairs
in find clause.
OR in MongoDB
Syntax
To query documents based on the OR condition, you need to use $or keyword. Following
is the basic syntax of OR −
>db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Example
Following example will show all the tutorials written by 'tutorials point' or whose title is
'MongoDB Overview'.
The following example will show the documents that have likes greater than 10 and whose
title is either 'MongoDB Overview' or by is 'tutorials point'. Equivalent SQL where clause
is 'where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')'
NOR in MongoDB
Syntax
To query documents based on the NOT condition, you need to use $not keyword.
Following is the basic syntax of NOT −
>db.COLLECTION_NAME.find(
{
$not: [
{key1: value1}, {key2:value2}
]
}
)
Example
db.empDetails.insertMany(
[
{
First_Name: "Radhika",
Last_Name: "Sharma",
Age: "26",
e_mail: "[email protected]",
phone: "9000012345"
},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Age: "27",
e_mail: "[email protected]",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Age: "24",
e_mail: "[email protected]",
phone: "9000054321"
}
]
)
Following example will retrieve the document(s) whose first name is not "Radhika" and
last name is not "Christopher"
> db.empDetails.find(
{
$nor:[
40
{"First_Name": "Radhika"},
{"Last_Name": "Christopher"}
]
}
).pretty()
{
"_id" : ObjectId("5dd631f270fb13eec3963bef"),
"First_Name" : "Fathima",
"Last_Name" : "Sheik",
"Age" : "24",
"e_mail" : "[email protected]",
"phone" : "9000054321"
NOT in MongoDB
Syntax
To query documents based on the NOT condition, you need to use $not keyword
following is the basic syntax of NOT −
>db.COLLECTION_NAME.find(
{
$NOT: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Example
Following example will retrieve the document(s) whose age is not greater than 25
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.
$type
The expr operator allows the use of aggregation expressions within the query language.
$jsonSchema
The mod operator selects the document where the value of a field is divided by a divisor
has the specified remainder.
$regex
It provides regular expression abilities for pattern matching strings in queries. The
MongoDB uses regular expressions that are compatible with Perl.
$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: db.books.find( { $text: { $search: "Othelo" } } )
$where
The "where" operator is used for passing either a string containing a JavaScript
expression or a full JavaScript function to the query system.
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> ]
},
$maxDistance: <distance in meters>,
$minDistance: <distance in meters>
}
}
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.
$elementMatch
The operator relates documents that contain an array field with at least one element
that matches with all the given query criteria.
$size
It selects any array with the number of the element specified by the argument.
It matches the documents where all the bit positions given by the query are clear infield.
$bitsAllSet
The bitallset operator matches the documents where all the bit positions given by the
query are set in the field.
$bitsAnyClear
The bitAnyClear operator matches the document where any bit of positions given by the
query is clear in the field.
It matches the document where any of the bit positions given by the query are set in the
field.
The $ operator limits the contents of an array from the query results to contain only the first
element matching the query document.
$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.
The meta operator returns the result for each matching document where the metadata
associated with the query.
$slice
The $ operator limits the contents of an array from the query results to contain only the first
element matching the query document.
$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.
The meta operator returns the result for each matching document where the metadata
associated with the query.
$slice
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.
$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.
$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.
$mul
$rename
$set
The set operator changes the value of a field with the specified value.
$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: db.collection.update(
<query>,
{ $setOnInsert: { <field1>: <value1>, ... } },
{ upsert: true }
})
$unset
Example: db.products.update(
{ sku: "unknown" },
{ $unset: { quantity: "", instock: "" } })
Array Operators
$
We can update an element in an array without explicitly specifying the position of the
element.
$[]
The positional operator indicates that the update operator should change all the elements
in the given array field.
$[<identifier>]
$addToSet
It adds an element to an array unless the element is already present, in which case this
operator does nothing to that array.
$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.
$pull
Using a pull operator, we can remove all the instances of a value in an array that matches
the specified condition.
$push
$pullAll
We can remove all instances of the specified value from existing array using the pullAll
operator. It removes element that match the listed value.
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.
$position
It specifies the location where the push operator inserts elements inside an array.
Syntax: {
$push:{
<field>: {
$each: [ <value1>, <value2>, ... ],
$position: <num>
}
}
Example: db.students.update(
{ _id: 1 },
{
$push: {
scores: {
$each: [ 50, 60, 70 ],
$position: 0
}
}
})
This modifier is used to limit the number of array elements during the push operation.
Syntax: {
$push: {
<field>: {
$each: [ <value1>, <value2>, ... ],
$slice: <num>
}
}
Example: db.students.update(
{ _id: 1 }, {
$push: {
scores: {
$each: [ 80, 78, 86 ],
$slice: -5
}
}
}
)
$sort
The sort modifier arranges the values of an array during the push operation.
Syntax: {
$push: {
<field>: {
$each: [ <value1>, <value2>, ... ],
$sort: <sort specification>
}
}
Example: db.students.update(
{ _id: 1 }, {
$push: {
quizzes: {
$each: [ { id: 3, score: 8 }, { id: 4, score: 7 }, { id: 5, score: 6 } ],
$sort: { score: 1 }
}
}
}
}
)
Bitwise Operator
$bit
The bit operator updates a field using a bitwise operation. It supports bitwise AND, bitwise
OR, and bitwise XOR operations.
Syntax
>db.COLLECTION_NAME.find().limit(NUMBER)
Example
Following example will display only two documents while querying the document.
>db.mycol.find({},{"title":1,_id:0}).limit(2)
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
>
If you don't specify the number argument in limit() method then it will display all
documents from the collection.
Syntax
The basic syntax of skip() method is as follows −
>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
Example
>db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL Overview"}
>
Syntax
>db.COLLECTION_NAME.find().sort({KEY:1})
Example
Following example will display the documents sorted by title in the descending order.
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"Tutorials Point Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>
Syntax
Basic syntax of aggregate() method is as follows −
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
Example
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by_user: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
},
{
_id: ObjectId(7df78ad8902d)
title: 'NoSQL Overview',
description: 'No sql database is very fast',
by_user: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 10
},
{
_id: ObjectId(7df78ad8902e)
title: 'Neo4j Overview',
description: 'Neo4j is no sql database',
by_user: 'Neo4j',
url: 'http://www.neo4j.com',
tags: ['neo4j', 'database', 'NoSQL'],
likes: 750
},
Now from the above collection, if you want to display a list stating how many tutorials are
written by each user, then you will use the following aggregate() method −
Sql equivalent query for the above use case will be select by_user, count(*) from mycol
group by by_user.
In the above example, we have grouped documents by field by_user and on each
occurrence of by user previous value of sum is incremented. Following is a list of available
aggregation expressions.
MS. ESHA PATEL Page 58
Unit-1: concepts of NoSQL: MongoDB
Pipleline Concept
In UNIX command, shell pipeline means the possibility to execute an operation on some
input and use the output as the input for the next command and so on. MongoDB also
supports same concept in aggregation framework. There is a set of possible stages and
each of those is taken as a set of documents as an input and produces a resulting set of
documents (or the final resulting JSON document at the end of the pipeline). This can
then in turn be used for the next stage and so on.
Following are the possible stages in aggregation framework −
$project − Used to select some specific fields from a collection.
$match − This is a filtering operation and thus this can reduce the amount of
documents that are given as input to the next stage.
$group − This does the actual aggregation as discussed above.
$sort − Sorts the documents.
$skip − With this, it is possible to skip forward in the list of documents for a given
amount of documents.
$limit − This limits the amount of documents to look at, by the given number
starting from the current positions.
$unwind − This is used to unwind document that are using arrays. When using an
array, the data is kind of pre-joined and this operation will be undone with this to
have individual documents again. Thus with this stage we will increase the amount
of documents for the next stage.