0% found this document useful (0 votes)
1K views

Mongo DB

The document discusses comparison operators in MongoDB that can be used to query documents, including $eq for equality, $gt and $gte for greater than/greater than or equal to, $lt and $lte for less than/less than or equal to, $ne for not equal, and $in to match values in an array. MongoDB uses these comparison operators as part of its query language to find documents matching specified criteria.

Uploaded by

pr so
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

Mongo DB

The document discusses comparison operators in MongoDB that can be used to query documents, including $eq for equality, $gt and $gte for greater than/greater than or equal to, $lt and $lte for less than/less than or equal to, $ne for not equal, and $in to match values in an array. MongoDB uses these comparison operators as part of its query language to find documents matching specified criteria.

Uploaded by

pr so
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 104

All of us do not have equal

talent. But, all of us have an


equal opportunity to develop
our talents.
A.P.J. Abdul Kalam

Database Technologies - MongoDB


Enterprise primaryDB> config.set("editor", "notepad+ iet
+")
Class Room

Session 1
Big Data?
Big data is a term that describes the large volume of data – both
structured and unstructured.

What is Big Data?


Big Data is also data but with a huge size. Big Data is a term used to describe a
collection of data that is huge in size and yet growing with time. In short such data is so
large and complex that none of the traditional data management tools are able to store it
or process it efficiently.

Characteristics Of Big Data


Big data is often characterized by the 3Vs: the extreme VOLUME of data, the
wide VARIETY of data and the VELOCITY at which the data must be
processed.
NoSQL
NoSQL database are primarily called as  non-SQL or non-relational database. MongoDB is
Scalable (able to be changed in size or scale), open-source, high-perform, document-oriented database.

Remember:
• Horizontal scaling means that you scale by adding more machines into your pool of resources.
• Vertical scaling means that you scale by adding more power (CPU, RAM) to an existing machine.
why NoSQL
when to use NoSQL
When should NoSQL be used:
• When huge amount of data need to be stored and retrieved .
• The relationship between the data you store is not that important
• The data changing over time and is not structured.
• Support of Constraints and Joins is not required at database level.
• The data is growing continuously and you need to scale the database regular to handle the data.

Remember:
• Data Persistence on Server-Side via NoSQL.
• Does not use SQL-like query language.
• Longer persistence
• Store massive amounts of data.
• Systems can be scaled.
• High availability.
• Semi-structured data.
• Support for numerous concurrent connections.
• Indexing of records for faster retrieval
NoSQL Categories
NoSQL Categories
There are 4 basic types of NoSQL databases.
Key-value stores, or key-value databases, implement a simple data model that pairs
a unique key with an associated value.
Key-value stores e.g.
• Redis, Cassandra

Wide-column stores organize data tables as columns instead of as rows.


e.g.
Column-oriented
• hBase

Document databases, also called document stores, store semi-structured data and
descriptions of that data in document format.
Document oriented e.g.
• MongoDB, CouchDB

Graph data stores organize data as nodes.


e.g.
Graph
• Neo4j
NoSQL Categories

Column-oriented Graph
An object is an unordered set of name/value pairs.

An array is an ordered collection of values.


SQL vs NoSQL Database

Relational databases are commonly referred to as SQL databases because they use SQL
(structured query language) as a way of storing and querying the data.

Difference:
• NoSQL databases are document based, key-value pairs, or wide-column stores. This means that
SQL databases represent data in form of tables which consists of n number of rows of data
whereas NoSQL databases are the collection of key-value pair, documents, or wide-column stores
which do not have standard schema definitions.
• SQL databases have predefined schema whereas NoSQL databases have dynamic schema for
unstructured data.
• SQL databases are vertically scalable whereas the NoSQL databases are horizontally scalable.
• SQL databases uses SQL ( structured query language ) for defining and manipulating the data. In
NoSQL database, queries are focused on collection of documents.
Types of Data
Structured Semi-Structured Unstructured

MongoDB stores documents (objects) in a format called BSON. 


BSON is a binary serialization of JSON
Types of Data
• Structured
The data that can be stored and processed in a fixed format is called as Structured Data. Data stored in a
relational database management system (RDBMS) is one example of  ‘structured’ data. It is easy to process
structured data as it has a fixed schema. Structured Query Language (SQL) is often used to manage such
kind of Data.

• Semi-Structured
Semi-Structured Data is a type of data which does not have a formal structure of a data model, i.e. a table
definition in a relational DBMS, XML files or JSON documents are examples of semi-structured data.

• Unstructured
The data which have unknown form and cannot be stored in RDBMS and cannot be analyzed unless it is
transformed into a structured format is called as unstructured data. Text Files and multimedia contents like
images, audios, videos are example of unstructured data.  
MongoDB  
MongoDB is a cross-platform document-oriented database program. Classified as a NoSQL database.
Remember:
• MongoDB documents are similar to JSON (key/fields and value pairs) objects.
• The values of fields may include other documents, arrays, or an arrays of documents.

Core MongoDB Operations (CRUD), stands for create, read, update, and delete.

SQL/MongoDB Terms:
MongoDB  
MongoDB stores data as BSON documents. BSON is a binary representation of JSON
documents.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy


for humans to read and write.
* MongoDB does not support duplicate field names

document
MongoDB stores data as BSON documents. BSON is a binary representation of
JSON documents.
document 
document 
MongoDB documents are composed of field-and-value pairs. The value of a field can be
any of the BSON data types, including other documents, arrays, and arrays of
documents.

The field name _id is reserved for use as a primary key; its value must be unique in the
collection, is immutable, and may be of any type other than an array.

{ The primary key _id is automatically added,


field1: value1, if _id field is not specified.
field2: value2,
field3: value3,
...
fieldN: valueN
}

Note:
• MongoDB does not support duplicate field names.
db
In the mongo shell, db is the variable that references the current database. The
variable is automatically set to the default database test or is set when you use
the use <db_name> to switch current database.
MongoDB Redis MySQL Oracle
Database Server mongod redis-server mysqld oracle
Database Client mongo redis-cli mysql sqlplus

start db server
start server and client 
To start MongoDB server, execute mongod.exe.
Note: Always give --dbpath in ""
• The --dbpath option points to your database directory.
• The --bind_ip_all option : bind to all ip addresses.
• The --bind_ip arg option : comma separated list of ip addresses to listen on, localhost by default.

--bind_ip <hostnames | ipaddresses>

mongod --dbpath "c:\database" --bind_ip_all --journal


mongod --dbpath "c:\database" --bind_ip stp10 --journal
mongod --dbpath "c:\database" --bind_ip 192.168.100.20 --journal
mongod --dbpath="c:\database" --bind_ip=192.168.100.20 –journal
mongod –auth --dbpath="c:\database" --bind_ip=192.168.100.20 --journal
mongod --storageEngine inMemory --dbpath "d:\tmp" --bind_ip 192.168.100.20
To start MongoDB client, execute mongo.exe.
must be empty folder
mongo "192.168.100.20:27017/db1"
mongo --host "192.168.100.20" --port "27017"
mongo --host "192.168.100.20" --port "27017" primaryDB
mongo --host="192.168.100.20" --port="27017" primaryDB
mongo --host="192.168.100.20" --port="27017" –u user01 -p user01 --
authenticationDatabase primaryDB
• db.version(); # version number
• db.getMongo(); # connection to 192.168.100.20:27017
• db.hostInfo(); # Returns a document with information about the mongoDB is runs on.
• db.stats(); # Returns DB status
• getHostName(); # stp5

comparison operator
comparison operator

$eq Matches values that are equal to a specified value.

$gt Matches values that are greater than a specified value.

$gte Matches values that are greater than or equal to a specified value.

$lt Matches values that are less than a specified value.

$lte Matches values that are less than or equal to a specified value.

$ne Matches all values that are not equal to a specified value.

$in Matches any of the values specified in an array.

$nin Matches none of the values specified in an array.


comparison operator
$eq $ne
{ field: { $eq: value } } { field: { $ne: value } }

$gt $gte
{ field: { $gt: value } } { field: { $gte: value } }

$lt $lte
{ field: { $lt: value } } { field: { $lte: value } }

$in
{ field: { $in: [ <value1>, <value2>, ..., <valueN> ] } }

$nin
{ field: { $nin: [ <value1>, <value2>, ..., <valueN> ] } }
logical operator
logical operator

Joins query clauses with a logical OR returns all documents that


$or
match the conditions of either clause.

Joins query clauses with a logical AND returns all documents that
$and
match the conditions of both clauses.

Inverts the effect of a query expression and returns documents that


$not
do not match the query expression.

{ $or: [ { <expr1> }, { <expr2> }, ..., { <exprN> } ] }

{ $and: [ { <expr1> }, { <expr2> }, ..., { <exprN> } ] }

{ field: { $not: { <operator-expression> } } }

• db.emp.find( { $or:[ { job: 'manager' }, { job: 'salesman' } ], $and:


[ { sal: {$gt:3000 }} ] }, { _id: false, ename: true, job: true, sal: true
} );
logical operator
$or
{ $or: [ { <expr1> }, { <expr2> }, ... , { <exprN> } ] }

• db.emp.find({$or: [{job: 'manager'}, {job: 'salesman'}]})

$and
{ $and: [ { <expr1> }, { <expr2> }, ... , { <exprN> } ] }

• db.emp.find({$and: [{job:'manager'}, {sal:3400}]})

$not
{ field: { $not: { <operator-expression> } } }

• db.emp.find({ job: {$not: {$eq: 'manager'}}})


ObjectId()
The ObjectId class is the default primary key for a MongoDB document
and is usually found in the _id field in an inserted document.

The _id field must have a unique value. You can think of the _id field as the
document’s primary key.
ObjectId()  
MongoDB uses ObjectIds as the default value of _id field of each document, which is
auto generated while the creation of any document.

ObjectId()

• x = ObjectId()
show databases
Print a list of all available databases.
show database 
Print a list of all databases on the server.

show { dbs | databases }


• show dbs
• show databases # Returns: all database name.

db.getName()
• db
• db.getName() # Returns: the current database name.
To access an element of an array by the zero-based index position, concatenate the
array name with the dot (.) and zero-based index position, and enclose in quotes

use database
Switch current database to <db>. The mongo shell variable db is set to
the current database.
use database 
Switch current database to <db>. The mongo shell variable db is set to the current database.

use <db>

• use db1
db.dropDatabase()
db.dropDatabase()
Removes the current database, deleting the associated data files.

db.dropDatabase()

• use db1
• db.dropDatabase()

Infoway Technologies, 3rd Floor Commerce Centre, Rambaug Colony, Paud Road Pune 411038
If not working then do changes in
my.ini file.
secure_file_priv = ""
• SELECT * FROM emp INTO OUTFILE "d:/emp.csv" FIELDS
TERMINATED BY ',';

mongoimport
mongoimport tool imports content from an Extended JSON, CSV, or TSV
export created by mongoexport, or another third-party export tool.
mongoimport - JSON 
The mongoimport tool imports content from an Extended JSON, CSV, or TSV export
created by mongoexport.

mongoimport < --host > < --port > < --db > < --collection > <
--type > < --file > < --fields "Field-List" > < --mode
{ insert | upsert | merge } > < --jsonArray > < --drop >

< --jsonArray > # if the documents are in array i.e. in [] brackets


< --drop > # drops the collection if exists

• C:\> mongoimport --host 192.168.0.3 --port 27017 --db db1 --collection


emp --type json --file "d:\emp.json"  
• C:\> mongoimport --host 192.168.0.6 --port 27017 --db db1 --collection
movies --type json --file "d:\movies.json" --jsonArray --drop
mongoimport - CSV 
The mongoimport tool imports content from an Extended JSON, CSV, or TSV export
created by mongoexport.

mongoimport < --host > < --port > < --db > < --collection > < --type >
< --file > < --fields "<field1>[,<field2>]*" < --headerline > > < --
useArrayIndexFields >

• C:\> mongoimport --host 192.168.100.20 --port 27017 --db db1 --collection emp --type csv
--file d:\emp.csv --headerline
• C:\> mongoimport --host 192.168.100.20 --port 27017 --db db1 --collection emp --type csv
--file d:\emp.csv --fields
"EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO,BONUSID,USERNAME,PWD"
• C:\> mongoimport --db db1 --collection o --type csv --file d:\emp.csv --fields
"EMPNO.int(32),ENAME.string(),JOB.string(),MGR.int32(),HIREDATE.date(2006-01-
02),SAL.int32(),COMM.int32(),DEPTNO.int32(),BONUSID.int32(),USERNAME.string(),PWD.string()"

Note:
• There should be no blank space in the field list.
e.g.
_id, ename, salary #this is an error
mongoimport - CSV 
The mongoimport tool imports content from an Extended JSON, CSV, or TSV export
created by mongoexport.

mongoimport < --host > < --port > < --db > < --collection > < --type >
< --file > < --fields "<field1>[,<field2>]*" < --headerline > > < --
useArrayIndexFields >

_id,course,duration,modules.0,modules.1,modules.2,modules.3
1,course1,6 months,c++,database,java,.net
2,course2,6 months,c++,database,python,R
3,course3,6 months,c++,database,awp,.net

• C:\> mongoimport --host 192.168.100.20 --port 27017 --db db1 --collection


course --type csv --file d:\course.csv --headerline --useArrayIndexFields
mongoexport
mongoexport is a utility that produces a JSON or CSV export of data
stored in a MongoDB instance.
mongoexport 
mongoexport is a utility that produces a JSON or CSV export of data stored in a
MongoDB instance..

mongoexport < --host > < --port > < --db > < --collection > < --type >
< --file > < --out >

• C:\> mongoexport --host 192.168.0.6 --port 27017 --db db1 --collection emp --
type JSON --out "d:\emp.json"
• C:\> mongoexport --host 192.168.0.6 --port 27017 --db db1 --collection emp --
type JSON --out "d:\emp.json" --fields "empno,ename,job"
• C:\> mongoexport --host 192.168.0.6 --port 27017 --db db1 --collection emp --
type CSV --out "d:\emp.csv" --fields "empno,ename,job"

Note:
• there should be no space in the field list.
e.g.
_id, ename, salary #this is an error
new Date()
TODO
new Date()  
MongoDB uses ObjectIds as the default value of _id field of each document, which is
auto generated while the creation of any document.

var variable_name = new Date()

• x = Date()
db.getCollectionNames()
Returns an array containing the names of all collections and views in
the current database.
db.getCollectionNames() 
getCollectionNames() returns an array containing the names of all collections in the current
database.

show collection
db.getCollectionNames()

• show collections
• db.getCollectionNames();
db.createCollection()
Creates a new collection or view.
db.createCollection() 
Capped collections have maximum size or document counts that prevent them from
growing beyond maximum thresholds. All capped collections must specify a maximum
size and may also specify a maximum document count. MongoDB removes older
documents if a collection reaches the maximum size limit before it reaches the
maximum document count. 

db.createCollection(name, { options1, options2, ... })

The options document contains the following fields:


• capped : boolean
• size : number
• max : number

• db.createCollection("log");
• db.createCollection("log", { capped: true, size: 1, max: 2}); //
This command creates a collection named log with a maximum size of 1 byte and a maximum
of 2 documents.
db.collection.isCapped()
Returns true if the collection is a capped collection, otherwise
returns false.
db.collection.isCapped()
isCapped() returns true if the collection is a capped collection, otherwise returns false. 

db.collection.isCapped()

• db.log.isCapped();
db.getCollection()
Returns a collection or a view object that is in the DB.
db.getCollection() 
TODO

db.getCollection('name')

• db.getCollection('emp').find();

• const auth = db.getCollection("author")


const doc = {
usrName : "John Doe",
usrDept : "Sales",
usrTitle : "Executive Account Manager",
authLevel : 4,
authDept : [ "Sales", "Customers"]
}

auth.insertOne( doc )
db.getSiblingDB()
To access another database without switching databases.
db.getSiblingDB()
Used to return another database without modifying the db variable in the shell environment. 

db.getSiblingDB(<database>)

• db.getSiblingDB('db1').getCollectionNames();
db.collection.renameCollection()
Renames a collection.
db.collection.renameCollection()
TODO

db.collection.renameCollection(target, dropTarget)

• db.emp.renameCollection('employee', false);

dropTarget : If true, mongod drops the target of renameCollection prior to renaming the
collection. The default value is false.
db.collection.drop()
Removes a collection or view from the database. The method also removes
any indexes associated with the dropped collection.
db.collection.drop()
drop() removes a collection or view from the database. The method also removes any indexes
associated with the dropped collection.

db.collection.drop(<options>)

• db.emp.drop();
Method Embedded Field Specification
.pretty() For fields in an embedded documents, you can specify the field using either:
dot notation; e.g. "field.nestedfield": <value>
nested form; e.g. { field: { nestedfield: <value> } }

For query on array elements:


array; e.g. '<array>.<index>'

db.collection.find()
The find() method always returns the _id field unless you specify _id: 0/false
to suppress the field.

By default, mongo prints the first 20 documents. The mongo shell will prompt the user to
Type "it" to continue iterating the next 20 results.

Enterprise primaryDB> config.set("displayBatchSize", 3)

• db.emp.find( { }, { _id: false, sal: true, Per : { $multiply: ['$sal', .05 ] },


NewSalary: { $add: ['$sal', { $multiply: [ '$sal', .05 ] } ] } } )
db.collection.find() 
TODO

db['collection'].find({ query }, { projection })


db.collection.find({ query }, { projection })
db.getCollection('name').find({ query }, { projection })

query: Specifies selection filter using query operators. To return all documents in a collection, omit this parameter or pass
an empty document ({}).
{ "<Field Name>": { "<Comparison Operator>": <Comparison Value> } }

projection: Specifies the fields to return in the documents that match the query filter. To return all fields in the matching
documents, omit this parameter.
{ "<Field Name>": <Boolean Value> } }

• 1 or true to include the field in the return documents. Non-zero integers are also treated as true.
• 0 or false to exclude the field.
db.collection.find() 
TODO '<array>.<index>
'
db['collection'].find({ query }, { projection })
db.collection.find({ query }, { projection })
db.getCollection('name').find({ query }, { projection })

• db.emp.find();
• db ['emp'].find ()
• db.getCollection('emp').find();
• db.getSiblingDB('db1').getCollection('emp').find();
• db.emp.find({job: 'manager'})
• db.emp.find({}, {ename: true, job: true});
• db.emp.find({sal:{ $gt: 4 }})
• db.emp.find({job: 'manager'}, {ename: true, job: true})
• db.emp.find({job: 'manager'}, {_id: false, ename: true, job: true})
db.collection.find() 
TODO '<array>.<index>
'
db['collection'].find({ query }, { projection })
db.collection.find({ query }, { projection })
db.getCollection('name').find({ query }, { projection })

• const query1 = { "job": "manager" };


• const query2 = { "sal": { $gt: 6000, $lt: 6500 } };
• const projection = { "_id" : false, "ename": true, "job": true, "sal":
true , "address": true };

• db.emp.find( query1, projection )


• db.emp.find( query2, projection )

TODO

delete < variable_name >


• delete query1
pattern matching with like in
db.collection.find() 
TODO

• db.movies.find({movie_title: /z/}, {_id:false, movie_title:true});


• db.movies.find({movie_title: /^z/}, {_id:false, movie_title:true});
• db.movies.find({movie_title: /z$/}, {_id:false, movie_title:true});
• db.movies.aggregate({ $match:{movie_title: /z$/}}, {$project:{_id:false,
movie_title:true}});
db.collection.find()[<index_number>] 
TODO

db['collection'].find({ query }, { projection }) [<index> [.field] ]


db.collection.find({ query }, { projection }) [<index> [.field] ]
db.getCollection('name').find({ query }, { projection }) [<index> [.field] ]

• db.emp.find()[0];
• db.emp.find()[0].ename;
• db.getCollection('emp').find() [0];
• db.emp.find()[db.emp.find().count()-1]
cursor with db.collection.find() 
In the mongo shell, if the returned cursor is not assigned to a variable using the var keyword,
the cursor is automatically iterated to access up to the first 20 documents that match the query.

var variable_name = db.collection.find({ query }, { projection })

The find() method returns a cursor.


var x = db['emp'].find()
x.forEach(printjson)
sort
Specifies the order in which the query returns matching documents. You
must apply sort() to the cursor before retrieving any documents from
the database.
db.collection.find().sort({ })
sort() specifies the order in which the query returns matching documents. You must apply
sort() to the cursor before retrieving any documents from the database.

cursor.sort({ field: value })


db['collection'].find({ query }, { projection }).sort({ field: value })
db.collection.find({ query }, { projection }).sort({ field: value })

Specify in the sort parameter


• 1 to specify an ascending sort.
• -1 to specify an descending sort.

• db['emp'].find({}, {ename: true}).sort({ename: 1});


• db['emp'].find({}, {ename: true}).sort({ename: -1});
limit
limit() method on a cursor to specify the maximum number of documents
the cursor will return.
A limit() value of 0 (i.e. limit(0)) db.collection.find().limit()
is equivalent to setting no limit.
limit() method specify the maximum number of documents the cursor will return.

cursor.limit(<number>)
db['collection'].find({ query }, { projection }).limit(<number>)
db.collection.find({ query }, { projection }).limit(<number>)

• db['emp'].find({}, { ename: true }).limit(0);# all documents


• db['emp'].find({}, { ename: true }).limit(2);
skip
skip() method on a cursor to control where MongoDB begins returning
results.
db.collection.find().skip()
skip() method is used for skipping the given number of documents in the Query result.

cursor.skip(<offset_number>)
db['collection'].find({ query }, { projection }).skip(<offset_number>)
db.collection.find({ query }, { projection }).skip( < offset_number > )

• db.emp.find().skip(4);
• db.emp.find().skip(db.emp.countDocuments({}) - 1);
count
Counts the number of documents referenced by a cursor. Append the
count() method to a find() query to return the number of matching
documents. The operation does not perform the query but instead counts
the results that would be returned by the query.
db.collection.find().count()
count() counts the number of documents referenced by a cursor. Append the count() method
to a find() query to return the number of matching documents. The operation does not
perform the query but instead counts the results that would be returned by the query.

cursor.count()
db['collection'].find({ query }).count()
db.collection.find({ query }).count()

• db.emp.find().count();
• db.emp.find({job: 'manager'}).count();
db.collection.distinct()
Finds the distinct values for a specified field across a single
collection or view and returns the results in an array.
db.collection.distinct()
distinct() finds the distinct values for a specified field across a single collection or view and
returns the results in an array.

db.collection.distinct("field", { query }, { options })

• db.emp.distinct("job")
• db.emp.distinct("job", { sal: { $gt: 5000 } } )

var x = db.emp.find()[10]
for (i in x) {
print(i)
}
db.collection.count[Documents]()
TODO
db.collection.count[Documents]() 
countDocuments() returns the count of documents that match the query for a
collection

db.collection.count[Documents]({ query }, { options })

Field Description

limit Optional. The maximum number of documents to count.

skip Optional. The number of documents to skip before counting.

• db.emp.count({});
• db.emp.countDocuments({});
• db.emp.countDocuments({job: 'manager'});
• db.emp.countDocuments({job: 'salesman'}, {skip: 1, limit: 3});
findOne
find() method always returns the _id field unless you specify _id:
0/false to suppress the field.
db.collection.findOne() 
findOne() returns one document that satisfies the specified query criteria on the collection. If
multiple documents satisfy the query, this method returns the first document according to the
order in which order the documents are stored in the disk. If no document satisfies the query, the
method returns null.

db['collection'].findOne({ query } , { projection })


db.collection.findOne({ query } , { projection })

• db.emp.findOne();
• db.emp.findOne({ job: 'manager' });
• If the document does not contain an _id field, then the save() method calls the insert()
method. During the operation, the mongo shell will create an ObjectId and assign it to
the _id field.
• If the document contains an _id field, then the save() method is equivalent to an update
with the upsert option set to true and the query predicate on the _id field.

db.collection.save()
Updates an existing document or inserts a new document, depending on
its document parameter.
db.collection.save()
save() UPDATES an existing document or INSERTS a new document, depending on its
document parameter.

db.collection.save({ document })

• db.x.save({_id: 10, firstName: 'neel', sal: 5000, color:


['blue', 'black' ], size: ['small', 'medium', 'large', 'xx-
large' ] })
db.collection.insert()
Inserts a document or documents into a collection.
db.collection.insert() or db.collection.insert([])
insert() inserts a single-document or multiple-documents into a collection.

db.collection.insert({<document>})
db.collection.insert([{<document 1>} , {<document 2>}, ... ])

• db.x.insert({})
• db.x.insert({ ename: 'ram', job: 'programmer ', salary:
42000 })
• db.x.insert([ { ename: 'sham'} , { ename: 'y' } ]) #
for multiple documents.

• const doc1 = { "name": "basketball", "category": "sports", "quantity":


20, "reviews": [] };
• const doc2 = { "name": "football", "category": "sports", "quantity":
30, "reviews": [] };
• db.x.insert([ doc1, doc2 ])
db.collection.insertOne() &
db.collection.insertMany()
Inserts a document into a collection.
Inserts multiple documents into a collection.
db.collection.insertOne() &
db.collection.insertMany([])
insertOne() inserts a single document into a collection.
insertMany() inserts a document or multiple documents into a collection.

db.collection.insertOne({<document>})
db.collection.insertMany([{<document 1>} , {<document 2>}, ... ])

• db.emp.insertOne({ ename: 'ram', job: 'programmer', salary: 2000 })


• db.emp.insertMany([ { ename: 'sham', salary: 2000}, { ename : 'raj', job:
'programmer' } ])

• const doc1 = { "name": "basketball", "category": "sports", "quantity": 20,


"reviews": [] };
• const doc2 = { "name": "football", "category": "sports", "quantity": 30,
"reviews": [] };
• db.x.insertMany([ doc1, doc2 ])
javascript object
TODO
javascript object
Inserts a document or documents into a collection using javascript object.

var obj = {}
> var doc = {}; # JavaScript object
> doc.title = "MongoDB Tutorial"
> doc.url = "http://mongodb.org"
> doc.comment = "Good tutorial video"
> doc.tags = ['tutorial', 'noSQL']
> doc.saveondate = new Date ()
> doc.meta = {} # object within doc object{}
> doc.meta.browser = 'Google Chrome'
> doc.meta.os = 'Microsoft Windows7'
> doc.meta.mongodbversion = '2.4.0.0'
> doc
> db.book.insert(doc);

> doc -> will print entire document.


> doc.Title -> will print only Title from document.
> print(doc) -> will print -> [object Object].
> print(doc.Title) -> will print only Title from document.
After executing a file with load(), you may reference any functions or variables
defined the file from the mongo shell environment.

load ("app.js")
Loads and runs a JavaScript file into the current shell environment.
load(file.js)
Specifies the path of a JavaScript file to execute.

load(file)
cat(file)

• function app(x, y) {
return (x + y);
}

• function app1(x, y, z) {
return (x + y + z);
}

• load("scripts/app.js")
• cat ("scripts/app.js")
javascript function
• db.emp.find({$or:[ {job:'manager'}, {job:'salesman'} ]}, {}).forEach(function(doc) {
print (doc.ename.padEnd(12, "-") + doc.job);
});

• db.emp.find().forEach(function(doc) { • db.emp.find().forEach(function(doc) {
if (doc.ename == 'saleel') { x = doc.job.split(" ");
print (doc.ename, doc.job); print (x[0]);
} else { });
quit;
};
});

• db.emp.find().forEach((doc) => {
if (doc.ename.length >= 7) {
print(doc.ename + ": " + doc.ename.length);
};
});

• db.emp.find().forEach(function(data) {
print("user: " + data.ename.toUpperCase();)
});
javascript function
• db.emp.find().forEach(function(doc) {
if(doc.job.split(' ')[1]=='Programmer' || doc.job=='programmer') {
print(doc.ename, doc.job);
}
});

• function findProductByID(_productID) {
return db.products.find({productID: _productID}, {_id:false,
productID:true, productname:true});
};

• function insertProduct(_productID, _productName, _color, _rate, _qty) {


db.product.insert({
productID:_productID,
productName:_productName,
color:_color,
rate:_rate,
qty:_qty,
total:_qty * _rate
});
};
javascript function
• function insertOnlyPune(id, _name, _sal, _comm, _city) {
if(_city == 'pune') {
db.abc.insertOne({
_id : id,
ename : _name,
sal: _sal,
comm : _comm,
grandSalary : _sal + _comm
})
};
};
javascript function
• function deleteProduct(_productID) {
db.product.deleteOne({_id:_productID});
};
javascript function
• function findProductByRangeID(_startID, _endID) {
return db.products.find({$and:[{productID:{$gte: _startID}},
{ productID:{$lte: _endID}}]}, {_id: false, productID: true,
productname: true });
};

• function productValidation(_productID) {
var x = db.products.find({productID:_productID}).count();
if (x != 0) {
return db.products.find({productID: _productID}, {_id:false,
productID:true, productname:true});
} else {
return ("Document not found!");
};
};
db.collection.update()
Modifies an existing document or documents in a collection. The method
can modify specific fields of an existing document or documents or
replace an existing document entirely, depending on the update
parameter. By default, the update() method updates a single document.
Set the Multi Parameter to update all documents that match the query
criteria.
db.collection.update()
By default, the update() method updates a single document. Set the multi Parameter to
update all documents that match the query criteria, an upsert means an update than inserts
a new document if no document matches the filter.

db.collection.update({ query }, { update }, { options })


db.collection.update({ query }, { $set:{ update }}, { options })

Options : { $set: { field: value } }, { multi: true, upsert: true }

• db.emp.update({ job: 'programmer' }, { job: 'sales' }, { upsert: true } );


• db.emp.update({ job: 'programmer' }, { $set: { job: 'sales' } }, { upsert :
true, multi: true });
• db.emp.update({ ename: 'ram' }, { $set : { size: 'small', color: ['red',
'blue'] } }, { multi: true } );
db.collection.updateOne()
updateOne() operations can add fields to existing documents using the
$set operator.
db.collection.updateOne()
updateOne() updates a single document within the collection based on the filter.

db.collection.updateOne({ filter }, { $set:{update} }, { options })

Options : { $set: { field: value } }, { upsert: true }

• db.emp.updateOne({ ename : 'ram' }, { $set : { job : 'programmer' } })


• db.emp.updateOne({ename : 'sham' }, { $set : { job : 'programmer' } },
{ upsert: true })
db.collection.updateMany()
updateMany() operations can add fields to existing documents using the
$set operator.
db.collection.updateMany()
updateMany() updates multiple documents within the collection based on the filter.

db.collection.updateMany({ filter }, { $set:{update} },


{ options })
Options : { $set: { field: value } }, { upsert: true }

• db.emp.updateMany({ sal: { $gt : 2000 } }, { $set: { color :


['red', 'yellow', 'green', 'blue'] } }, { upsert: true } );
db.collection.deleteOne()
Removes a single document from a collection.
db.collection.deleteOne()
deleteOne() removes a single document from a collection. Specify an empty document { } to
delete the first document returned in the collection.

db.collection.deleteOne({ filter })

• db.emp.deleteOne({})
• db.emp.deleteOne({ job: 'manager' })
db.collection.deleteMany()
Removes all documents that match the filter from a collection.
db.collection.deleteMany()
deleteMany() removes all documents that match the filter from a collection.

db.collection.deleteMany({ filter })

• db.emp.deleteMany({});
• db.emp.deleteMany({ job: 'manager' });
“Accept your past without regret,
handle our present with confidence
and face your future without fear.“
A.P.J. Abdul Kalam

You might also like