You are on page 1of 52

NoSQL

Basic Commands
PREPARED BY: PIDOCTOR, MIT
MARCH 25, 2022
DATABASE
(Create, Drop Command)

 use
 use DATABASE_NAME is used to create database. The command will create
a new database if it doesn't exist, otherwise it will return the existing
database.

 db
 To check your currently selected database, use the command db

 Show dbs
 If you want to check your databases list, use the command show dbs.
DATABASE

 dropDatabase()
 db.dropDatabase() command is used to drop a existing database.
 1. First, check the list of available databases by using the command, show
dbs.
 2. Go to the database you want to delete by using the USE command then
execute db.dropDatabase()
COLLECTION
(Create, Drop Command)

 MongoDB db.createCollection(name, options) is used to create


collection.
Syntax: db.createCollection(name, options)
Example: db.createCollection(“sampletable”)
 In MongoDB, you don't need to create collection. MongoDB
creates collection automatically, when you insert some document.
 db.sampletable.insert({"name" : “Philip Doctor"}
COLLECTION

 drop()
 db.collection.drop() is used to drop a collection from the database.
 Syntax: db.yourCOLLECTIONname.drop()
 1. First, check the available collections into your database using the show
collections command
 2. Use the db.yourcollectionname.drop()
DOCUMENT
(insert)

 To insert data into MongoDB collection, you need to use


MongoDB's insert() or save() method.
 Syntax: db.COLLECTION_NAME.insert(document)
 Example:
Db.sampletable.insert({ "Title" : "MongoDb", "Description" : "Database
Programming", "By" : "juan dela cruz“})
To insert the document you can use db.samplecollection.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.
DOCUMENT
(query)

 Find()
 To query data from MongoDB collection, you need to use MongoDB's find() method.

Syntax: db.samplecollection.find()
 Pretty()
 To display the results in a formatted way, you can use pretty() method.

Syntax: db.samplecollection.find().pretty()
DOCUMENT
(update)

 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.
 Update()
 The update() method updates the values in the existing document.
 Syntax:
db.samplecollection. update(SELECTION_CRITERIA, UPDATED_DATA)
DOCUMENT
(update)
 SAMPLE:
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}

Lets update { "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}


 db.sampleCollection.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})

By default, MongoDB will update only a single document. To update multiple


documents, you need to set a parameter 'multi' to true.
 db.sampleCollection.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB
Tutorial'}},{multi:true})
DOCUMENT
(delete)

 remove()
MongoDB's remove() method is used to remove a document from the
collection. remove() method accepts two parameters. One is deletion
criteria and second is justOne flag.
deletion criteria − (Optional) deletion criteria according to
documents will be removed.
justOne − (Optional) if set to true or 1, then remove only one
document.
 Syntax: db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
DOCUMENT
(delete)

 Example:
{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}

Lets remove {_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},


db.sampleCollection.remove({'title':'MongoDB Overview'})
DOCUMENT
(delete)

 Remove Only One


If there are multiple records and you want to delete only the first record,
then set justOne parameter in remove() method.
db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
 Remove All Documents
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.sampleCollection.remove({})
NOSQL
Commands(Part 2)
PREPARED BY: PHILIP I DOCTOR, MIT
MARCH APRIL 1,2022
insertOne() method
 Syntax: db.COLLECTION_NAME.insertOne(document)
db.empDetails.insertMany(

insertMany() [
{
First_Name: “Juan ",
method Last_Name: “Cruz",
Date_Of_Birth: "1995-09-26",
e_mail: “JC@gmail.com",
 Following example phone: “001234"
},
inserts three different {
documents into the First_Name: "Rachel",
empDetails collection Last_Name: “Paterson",
using the insertMany() Date_Of_Birth: "1990-02-16",
e_mail: “RP123@gmail.com",
method. phone: “1002345"
},
{
First_Name: “Jason",
Last_Name: “Momoa",
Date_Of_Birth: "1990-02-16",
e_mail: “aquaman@gmail.com",
phone: "9000054321"
}
]
}
Insert() vs inserTOne() vs
InsertMany()
 Inserts a document or documents into a collection and returns
a WriteResult object for single inserts and a BulkWriteResult object for
bulk inserts.
 The insert() returns a WriteResult() object that contains the status of the
operation. Upon success, the WriteResult() object contains information on the
number of documents inserted:
Example: WriteResult({ "nInserted" : 1 }

 The insert() method is deprecated in major driver so you should use


the the .insertOne() method whenever you want to insert a single
document into your collection and the .insertMany() when you want
to insert multiple documents into your collection.
findOneAndUpdate(),updateOne()
,updateMany()
 Syntax:
>db.COLLECTION_NAME.findOneAndUpdate(SELECTION_CRITERIA,
UPDATED_DATA)
 findOneAndUpdate returns a document whereas updateOne does
not (it just returns the _id if it has created a new document).
$set $unset operators

 These operators are use as field update operators


 The $set operator replaces the value of a field with the specified
value.
 The $unset operator deletes a particular field.

Example: db.students.updateOne({_id:5},{$unset:{age:””}})
This command will remove age field with document _id:5 of in your
collection
Projection
 projection means selecting only the necessary data rather than
selecting whole of the data of a document. If a document has 5 fields
and you need to show only 3, then select only 3 fields from them.
 the find() method, explained in on previous meeting accepts second
optional parameter that is list of fields that you want to retrieve. In
MongoDB, when you execute find() method, then it displays all fields of
a document. To limit this, you need to set a list of fields with value 1 or 0.
1 is used to show the field while 0 is used to hide the fields.
 Syntax:
db.COLLECTION_NAME.find({},{KEYyouwanttobeShown:1,KEYyouwantN
ottobeShown:0})
 Example: db.mycol.find({},{"title":1,_id:0,”color”:1})
Limit() method

 To limit the records in MongoDB, you need to use limit() method. The
method accepts one number type argument, which is the number
of documents that you want to be displayed
 Syntax: >db.COLLECTION_NAME.find().limit(NUMBER)
 Note: If you don't specify the number argument in limit() method
then it will display all documents from the collection.
Sort() Method

 Sort() methods sorts documents in MongoDB. The method accepts a


document containing a list of fields along with their sorting order. To
specify sorting order 1 and -1 are used. 1 is used for ascending order
while -1 is used for descending order.
 Syntax: db.COLLECTION_NAME.find().sort({KEY:1})
 Example: db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
Logical Operations
Operation Syntax Example RDBMS Equivalent
Equality {<key>:{$eg;<value>}} db.mycol.find({"by":"tutorials where by = 'tutorials
point"}).pretty() point'

Less Than {<key>:{$lt:<value>}} db.mycol.find({"likes":{$lt:50}}). where likes < 50


pretty()

Less Than Equals {<key>:{$lte:<value>}} db.mycol.find({"likes":{$lte:50}} where likes <= 50


).pretty()

Greater Than {<key>:{$gt:<value>}} db.mycol.find({"likes":{$gt:50}} where likes > 50


).pretty()
Logical Operations
Operation Syntax Example RDBMS Equivalent
Greater Than {<key>:{$gte:<value>}} db.mycol.find({"likes":{$gte:50 where likes >= 50
Equals }}).pretty()

Not Equals {<key>:{$ne:<value>}} db.mycol.find({"likes":{$ne:50}} where likes != 50


).pretty()
AND in MongoDB

 To query documents based on the AND condition, you need to use


$and keyword. Following is the basic syntax of AND −

Syntax: db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>} ]


})
OR in MongoDB

 To query documents based on the OR condition, you need to use $or keyword.
Following is the basic syntax of OR −
 Syntax: >db.mycol.find( {$or: [{key1: value1}, {key2:value2}]}).pretty()
Activity:

 Create a database about Student with the following key:


 Lastname, Firstname, Section, Age, Gender , NoOfSiblings
 Create at least 10 documents with customize id(example: 1,2,3,4…)
 (make sure the first document is your REAL STUDENT NAME

A. Arrange and display all the documents from highest to lowest by their _ID.
B. Display all documents between id number 5 and id number 12(logical operators)
C. Display and limit your documents to 4 documents only.
To be submitted:
Screen shots of A, B, C
NoSQL
Indexing and Text
Search
PREPARED BY: PHILIP I DOCTOR, MIT
APRIL 04, 2022
BSIT-2A
INDEXING
 Indexes are special data structures, that store a small portion of the data set in an easy-to-
traverse form. The index stores the value of a specific field or set of fields, ordered by the value
of the field as specified in the index.
 To create an index, you need to use createIndex() method of MongoDB.
Syntax:
db.COLLECTION_NAME.createIndex({KEY:1})
Example:
>db.mycol.createIndex({"title":1})
In createIndex() method you can pass multiple fields, to create index on multiple fields.
>db.mycol.createIndex({"title":1,"description":-1})
INDEXING
dropIndex() method

 You can drop a particular index using the dropIndex() method of MongoDB.
Syntax:
db.COLLECTION_NAME.dropIndex({KEY:1})
Example:
db.mycol.dropIndex({"title":1})
 Here key is the name of the file on which you want to create index and 1 is for
ascending order. To create index in descending order you need to use -1.
INDEXING
dropIndexes() method

This method deletes multiple (specified) indexes on a collection.


Syntax:
db.COLLECTION_NAME.dropIndexes()
Example:
Assume we have created 2 indexes in the named mycol collection as shown below
db.mycol.createIndex({"title":1,"description":-1})
Following example removes the above created indexes of mycol −
db.mycol.dropIndexes({"title":1,"description":-1})
Result:
{ "nIndexesWas" : 2, "ok" : 1 }
To remove all the indexes:
Db.mycol.dropIndexes()
INDEXING
getIndexes() method

This method returns the description of all the indexes int the collection.
Syntax:
db.COLLECTION_NAME.getIndexes()
Example:
Assume we have created 2 indexes in the named mycol collection as shown below
1. db.mycol.createIndex({"title":1,"description":-1})
to get the list of indexes:
>db.mycol.getIndexes()
TEXT SEARCH
Text search is a technique in mongodb where we can find a piece of text or a specified word from the
string fields. It allows us to perform a query operation to find the specified text from the string.
Text index: Text indexes should be either a string or an array of string elements. When you perform a text
search query always remember that your collection must contain a text index and a collection can only contain
one text index but this single text index covers multiple fields. We can create a text index
using createIndex() method.
Syntax:
db.collectionName.createIndex( { field: “text” } )
Example:
db.artist.find().pretty()
{ "_id" : 1, "artist" : "AA", "motto" : "I love cats and dogs" }
{ "_id" : 2, "artist" : "BB", "motto" : "I dont love cats by i like dogs" }
{ "_id" : 3, "artist" : "CC", "motto" : "I love dogs and cows" }

Let’s create an index on artist and motto


> db.artist.createIndex({artist:"text",motto:"text")
TEXT SEARCH
Now that we have created the text index on motto field, we will search for all the posts
having the word dogs in their text.

 db.artist.find({$text:{$search:"dog"}})
Output:
{ "_id" : 1, "artist" : "AA", "motto" : "I love cats and dogs" }
{ "_id" : 2, "artist" : "BB", "motto" : "I don’t love cats by i like dogs" }
{ "_id" : 3, "artist" : "CC", "motto" : "I love dogs and cows" }
search phrases
 Instead of searching a single word you are also allowed to search for a phrase by
wrapping the phrase in double quotes(“”). Generally, the phrase search performs
OR operation in between the specified keywords. For example, the phrase is “I like
Mango”, then phase search looks for all the documents that contain keywords
either I, like, or Mango. And if you want to perform an exact phrase search then
wrap the phase in between escaped double quotes(\”).

For exact phrase search:


db.collectionName.find({$text:{$search:”\”Phrase”\”}})
Example:
> db.artist.find({$text:{$search:"\"i love dogs\""}})
Output:
{ "_id" : 3, "artist" : "CC", "motto" : "I love dogs and cows" }
Text exclusion

 Exclusion of term means when you perform search operation and


does not want to display the document that contains the specified
term, so you can exclude the term by prefixing a search keyword
with the minus sign(-). Using minus sign(-) you can exclude all the
documents that contain exclude term. For example, you want to
display all the documents that contain the keyword “Car” but not
the “Cycle” keyword so you can use the following query:
Example:
db.collectionName.find({$text:{$search:"Car -Cycle"}})
CPC 223A
DATABASE PROGRAMMING
PREPARED BY: PI DOCTOR,MIT

MARCH 14, 2022


DATABASE

 a database is an organized collection of data stored and accessed


electronically.
Category of Database

 RELATIONAL DATABASE
 Microsoft SQL Server, Oracle Database, MySQL and IBM DB2.
 Cloud relational databases- Amazon Relational Database Service,
Google Cloud SQL, IBM DB2 on Cloud, SQL Azure and Oracle Cloud.

 NON RELATIONAL DATABASE (NoSQL)


 NoSQL or non-relational databases examples: MongoDB, Apache
Cassandra, Redis, Couchbase, Apache Hbase, BigTable, Redis,
RavenDb, Cassandra, Neo4j
 DIFFERENCE:
 main difference : How they store their information.
Storage

 A relational database typically stores information in tables


containing specific pieces and types of data.
 Relational databases use Structured Query Language
(SQL).
 the database usually contains tables consisting of columns
and rows.
 When new data is added, new records are inserted into
existing tables or new tables are added.
 Relationships can then be made between two or more
tables.
 Relational databases work best when the data they
contain doesn’t change very often, and when accuracy is
crucial. Relational databases are, for instance, often found
in financial applications.
Storage

 Non relational Database(No SQL) store its


data in a non-tabular form. Instead, non-
relational databases might be based on data
structures like documents.
 A document can be highly detailed while
containing a range of different types of
information in different formats.
NoSQL
 Stands for Not Only SQL
 Ability to store large amounts of data with little structure.
 Scalability and flexibility to meet changing business requirements.
 Schema-free or schema-on-read options.
 Capture all types of data “Big Data” including unstructured data.
 Document oriented.
 Best for Rapid Application Development. NoSQL is the best selection for flexible data
storage with little to no structure limitations.
 Provide flexible data model with the ability to easily store and combine data of any
structure without the need to modify a schema.
What is Big Data

 A term for data sets that are so large than traditional methods of
storage & processing are inadequate.
 Wikipedia: a collection of data that is huge in volume, yet growing
exponentially with time. It is a data with so large size and complexity
that none of traditional data management tools can store it or
process it efficiently. Big data is also a data but with huge size.
 Massive increase in data volumes since the start of the Internet Era
 Social Networks (Facebook,Insta,Tiktok etc), Search
Engines(Google) that stores tons of data.
 Challeges in storages,captures, analysis,transfer etc.
Advantages of NoSQL over RDMS

 Handles Big Data


 Data Models are Flexible- No Predefined Schema(No need to
define database define table, define datatype)
 Data Structure- NoSQl handles unstructured data(you don’t need to
plan what should be in the table)
 Cheaper to manage
 Scaling(Scalibility)
Scalability
 In electronics (including hardware, communication and software), scalability is the
ability of a system to expand to meet your business needs. For example scaling a
web application is all about allowing more people to use your application. You scale
a system by upgrading the existing hardware without changing much of the
application or by adding extra hardware.

There are two ways of scaling horizontal and vertical scaling :
 Vertical scaling
To scale vertically (or scale up) means to add resources within the same logical unit
to increase capacity. For example to add CPUs to an existing server, increase
memory in the system or expanding storage by adding hard drive.
 Horizontal scaling
To scale horizontally (or scale out) means to add more nodes to a system, such as
adding a new computer to a distributed software application. In NoSQL system, data
store can be much faster as it takes advantage of “scaling out” which means to add
more nodes to a system and distribute the load over those nodes.
Scaling(The Building example)

• Relational DATABASE Scales Vertically Non Relational Database can Scale


Horizontally
SQL VS NoSQL

 SQL databases are relational, NoSQL are non-relational.


 SQL databases use structured query language and have a
predefined schema. NoSQL databases have dynamic schemas for
unstructured data.
 SQL databases are vertically scalable, NoSQL databases are
horizontally scalable.
 SQL databases are table based, while NoSQL databases are
document, key-value, graph or wide-column stores.
 SQL databases are better for multi-row transactions, NoSQL are
better for unstructured data like documents or JSON.
Types of NOSQL Databases

 Document Databases(MongoDB, CouchDB)it stores data in JSON


format
 Column Database*Apache Cassandra)
 Key Value Stores (Redis, CouchBase Server)
 Cache Systems (Redis, Memcache)
 Graph Database(NEO4J)
Relational vs Document DB
MONGODB
 MongoDB is a cross-platform, document oriented database that provides, high
performance, high availability, and easy scalability. MongoDB works on concept of
collection and document.

 Database is a physical container for collections. Each database gets its own set of files on the
file system. A single MongoDB server typically has multiple databases.
 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.
 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

Table Join Embedded Documents

Primary Key Primary Key (Default key _id provided by


MongoDB itself)
Where to Use MongoDB?

 Big Data
 Content Management and Delivery
 Mobile and Social Infrastructure
 User Data Management
 Data Hub
 Next: MongoDB Installation
 mongoDB Compass
 mongoDb Shell

Thankyou.

You might also like