KEMBAR78
MongoDB Lab | PDF | Databases | No Sql
0% found this document useful (0 votes)
12 views11 pages

MongoDB Lab

Uploaded by

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

MongoDB Lab

Uploaded by

vaniv81
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

MongoDB –commands

MongoDB is a NoSQL document based database. Essentially, all


the data in MongoDB is stored in JSON documents that are sorted
into a variety of collections based on the type of data. It is one of
the most popular NoSQL database options due to its relative ease
of use and power.

Getting Started

In order to get started with MongoDB we first need to install


MongoDB to our computers. You also need a way to interact with
MongoDB as well which is where the command line tool Mongosh
comes in. When installing MongoDB make sure to download the
community edition and not the enterprise edition. Below are
download links for both of these tools.

MongoDB: https://docs.mongodb.com/manual/installation
Mongosh: https://docs.mongodb.com/mongodb-shell/install

Once you install these two tools just open up a terminal and
type mongosh to start working with MongoDB.

Basic terminology related to MongoDB databases:

Database

A database is simply a container for collections. A database in


MongoDB is the same conceptually as a database in SQL and
usually a project will have one database full of different
collections.

Collection

A collection is a grouping of documents inside a database. This is


the same conceptually as tables in a SQL database. Usually you
will have one collection per data model. For example, your app
may have users, posts, and products collections.
Document

A document is just a record inside of a collection. This is


conceptually the same as a row in a SQL table. A document
generally represents one single object within a collection. In
MongoDB a document is essentially just a JSON object.

Field

A field is just a key value pair within a document. This is


conceptually the same as a column in SQL. Each document
contains a number of fields which contain information such as
name, address, hobbies, etc. An important difference between
SQL and MongoDB is that a field can contain values such as JSON
objects and arrays instead of just strings, numbers, booleans, etc.
Also, MongoDB documents can have different fields defined within
the same collection. In SQL all rows in a table must have the
same columns, but in MongoDB one document in the users
collection could have the fields name, and age, while another user
document could have the fields name, address, and hobbies

Basic Commands

Mongosh:

The first command is the mongosh command. This command is


run in the terminal and gives us direct access to our local
MongoDB installation.

show dbs
The show dbs command is a simple command that shows all
MongoDB databases. If you run this you will notice that there are
already some databases that were created when you installed
MongoDB.
use <dbname>
This command lets you switch to a database based on
the dbname variable. For example, use mydb will switch you to
the mydb database. If there is no database with that name it will
still swap you to that db and if you later add any data it will
automatically create the db and add the data to it. Unlike SQL,
MongoDB has no commands to create data/collections since they
are automatically created when you add data.
db

This command just prints out the current database name.


cls

This command clears the terminal screen.


show collections
If you are connected to a database you can run show collections to
print out information on all the collections in that database.
db.dropDatabase()

This command will delete the current database and all the data
within it. You will also notice this command looks a lot like
JavaScript code. This is actually true of many commands in
MongoDB..
exit
The last basic command is the exit command which just exits
the mongosh session that you started with the mongosh command.

CRUD Methods
The following commands will be all the Create, Read, Update, and
Delete commands you need to know in MongoDB. All of these
commands will be run on a specific collection within a specific
database. For example to get all the records in the users table
within the current db you would write db.users.find().

Create

Creating documents in MongoDB is actually pretty simple since


there are only two methods to do so and they both are very
similar.
insertOne
This function takes a single object and creates a document with
the specified information within the specified collection. You also
notice we don’t pass an ID when we create documents. This is
because every MongoDB document automatically has
an _id property added to it with a unique id.
insertMany
This function works just like insertOne, but it takes an array of
objects to be inserted instead.

Read

Reading data within MongoDB is much more complicated and is


where almost all the confusion around MongoDB comes from.
find
If you want to get all the documents within a single collection you
can use the find method with no additional parameters.

find(<filterObject>)
Generally when you get documents you only want to get some of
them. If you pass an object to the find method it will return all
documents that match that filter object. By default the filter
object will do equality comparisons and if you pass multiple fields
in the same filter object it will only return documents that match
all the fields in the filter.
The final way to use the find method is by passing a second
object to select which fields you want returned. The object
contains a key which is the field and a value of either 0 or 1 to
determine if that field is returned or not. By default
the _id property is always returned unless specifically told not.

findOne

This is the same as find in every way except it just returns the
first document that matches the filter.

countDocuments

This final method returns the count of all documents that match
the filter passed to it.

Update

Updating documents in MongoDB is a bit more complex than in


SQL since there are actually many different ways you can update
a document.
updateOne
The main way to update a document is with the updateOne function.
This will update the first document that matches the filter passed
to it and will then update the document based on the information
passed in the second parameter to updateOne.

updateMany
This works exactly the same as updateOne, but it will update all
documents that match the filter object instead of just the first.

replaceOne
This works similarly to updateOne, but it will instead replace the
entire document and not just update specific fields. Generally this
is not something you want to do as it will delete all fields in the
object (except the id field) that are not specified within the object
passed to replaceOne.

Delete

deleteOne

This method will delete the first object that matches the filter
object passed to it.
deleteMany
This is the same as deleteOne but it will delete all documents that
match the filter object instead of just one.

_________________________--

Case study1: Create a student database and perform


typical CRUD operations in MongoDB

https://github.com/vanivega/BIg_data_analytics/blob/
main/Student_DB_MongoDB

use Student

db.createCollection('std')

db.std.insertMany([{SNO:1,SNAME:"Asmi",DEGREE:"BCA",SEM:6,C
GPA:9},

{SNO:2,SNAME:"Awani",DEGREE:"MCA",SEM:7,CGPA:8},

{SNO:3,SNAME:"Archi",DEGREE:"BTECH",SEM:2,CGPA:7.2},

{SNO:4,SNAME:"Riya",DEGREE:"BCA",SEM:3,CGPA:9},

{SNO:5,SNAME:"Srasti",DEGREE:"MTECH",SEM:4,CGPA:4},

{SNO:6,SNAME:"Anushka",DEGREE:"MCA",SEM:7,CGPA:9},
{SNO:7,SNAME:"Rashi",DEGREE:"BA",SEM:8,CGPA:9.5},

{SNO:8,SNAME:"Muskan",DEGREE:"BSC",SEM:4,CGPA:8.7},

{SNO:9,SNAME:"Priya",DEGREE:"BCA",SEM:3,CGPA:6.9},

{SNO:10,SNAME:"Khushi",DEGREE:"BCA",SEM:2,CGPA:7.8}]

//Q1.Display all the students

db.std.find()

//Q2.Display all the students in BCA

db.std.find({"DEGREE":"BCA"})

//Q3.Display all students in ascending order

db.std.find().sort({SNAME:1})

//Q4.Display first 5 students

db.std.find().limit(5)

//Q5. Display Students 5 6 7

db.std.find({SRN:{$in:[5,6,7]}})

//Q6.list the degree of student Rohan

db.std.find({SNAME:"Rohan"},{DEGREE:1,_id:0})
//Q7.Display students details of 5,6,7 in descending order of
percentage

db.std.find({SRN:{$in:[5,6,7]}}).sort({"CGPA":-1})

//Q8. Display the number of students in BCA

db.std.find({DEGREE:"BCA"}).count()

//Q9. Display all the degrees without _id

db.std.find({},{DEGREE:1,_id:0})

//Q10. Display all the distinct degrees

db.std.distinct("DEGREE")

//Q11. Display all the BCA students with CGPA greater than 6, but
less than 7.5

db.std.find(DEGREE:"BCA",{CGPA:{$gt:6, $lt:7.5}})

//Q12 Display all the students in BCA and in 6th SEM

db.std.find({$and:[{DEGREE:"BCA"},{SEM:6}]})

refer:

https://www.mongodb.com/resources/products/fundamentals/
examples
Consider a table “Students” with following columns:

1.StudRollNo 2.StudName 3.Grade 4.Hobbies 5.DOJ

Demonstrate Create, Read,Update and Delete(CRUD) operation in


MongoDB.Compare with RDBMS

Find the documents from Students collection where StudName


has an “e” in any position.

Find the document from Students collection where StudName


ends in “a”

Create a student document. Insert the document for “Aryan


david” into student collection only if it does not exists already.
However, if already present update the document with new value.
Use Update else insert

Write MongoDB Queries to:

• Create a collection by name “Person”.

• Drop a collection by name “”food”

• Create a collection by name “Students” and store following


data into it:StudName, Grade, Hobbies

Demonstrate Save method to insert a document for student


“XYZ” in “students” collection. Omit providing value for _id key

Demonstrate Update method to insert document “ABC” into


Students collection. Frst try upsert false and then set to True

Demonstrate adding a new field “Newark” to document of student


s collection. Confirm the new field “location” with value “Newark”
had been added to the document in “students” collection

Demonstrate removing of field “location” with value “Newark” in


the document of students collection

Demonstrate search for documents from Students collection


based on certain search criteria

Display only StudNAme from all documents of Students collection.


The identifier _id should be suppressed and not displayed
Display only studname and grade from all documents of students
collection. Identifier should be suppressed and not displayed

Display StudName and Grade and Identifier _id from document of


Students collection where _id column is 1. The _id field should not
be displayed.

Find the documents where grade is set to VII

Find the documents where grade is set to VII


Find the documents from Students collection where hobbies is
either set to Chsess or Skating

You might also like