0% found this document useful (0 votes)
11 views33 pages

MST 4

This document provides an overview of MongoDB, including its structure, installation options, and how to use the MongoDB Shell (mongosh) for database operations. It covers creating databases and collections, inserting, finding, updating, and deleting documents, as well as querying data with various methods. Additionally, it explains the MongoDB Query API and its capabilities for data manipulation and retrieval.

Uploaded by

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

MST 4

This document provides an overview of MongoDB, including its structure, installation options, and how to use the MongoDB Shell (mongosh) for database operations. It covers creating databases and collections, inserting, finding, updating, and deleting documents, as well as querying data with various methods. Additionally, it explains the MongoDB Query API and its capabilities for data manipulation and retrieval.

Uploaded by

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

Module Overview

Documents Database Overview

Understanding JSON
Understand BSON
Extended JSON
MongoDB Structure
MongoDB Architecture
MongoDB Remote Management

Installation Options
Installation on Windows
Create MongoDB Atlas Cluster
GUI tools Overview
MongoDB Shell JavaScript Engine
MongoDB Shell JavaScript Syntax
Arguments in the MongoDB Method

Introduction to the MongoDB Types


_id
ObjectId

Exploring Databases and Collections


Install MongoDB Shell (mongosh)
There are many ways to connect to your MongoDB database.

We will start by using the MongoDB Shell, mongosh.

To verify that it has been installed properly, open your terminal and type:

CMD >>mongosh–version

Connect to the database


To connect to your database, you will need your database specific connection
string.

In the MongoDB Atlas dashboard, under "Databases", click the "Connect" button
for your Cluster.

Next, choose "Connect with the MongoDB Shell".

Copy your connection string.

CMD >>mongosh "mongodb+srv://cluster0.ex4ht.mongodb.net/myFirstDatabase" --apiVersion 1


--username YOUR_USER_NAME

MongoDB Query API


The MongoDB Query API can be used two ways:

● CRUD Operations
● Aggregation Pipelines

You can use the MongoDB Query API to perform:

● Adhoc queries with mongosh, Compass, VS Code, or a MongoDB driver for


the programming language you use.
● Data transformations using aggregation pipelines.
● Document join support to combine data from different collections.
● Graph and geospatial queries.
● Full-text search.
● Indexing to improve MongoDB query performance.
● Time series analysis.

MongoDB mongosh Create


Database
Create Database using mongosh

After connecting to your database using mongosh, you can see which database you are using by typing
db in your terminal.

If you have used the connection string provided from the MongoDB Atlas dashboard, you should be
connected to the myFirstDatabase database.

Show all databases. To see all available databases, in your terminal type show dbs.

Notice that myFirstDatabase is not listed. This is because the database is empty. An empty database is
essentially non-existant.

Change or Create a Database. You can change or create a new database by typing use then the name of
the database.

Example

Create a new database called "blog":

CMD >>use blog

We are now in the blog database.

MongoDB mongosh Create


Collection
Create Collection using mongosh
There are 2 ways to create a collection.

Method 1
You can create a collection using the createCollection() database method.

Example
db.createCollection("posts")

Try it Yourself »

Method 2
You can also create a collection during the insert process.

Example
We are here assuming object is a valid JavaScript object containing post data:

db.posts.insertOne(object)

This will create the "posts" collection if it does not already exist.

MongoDB mongosh Insert


Insert Documents
There are 2 methods to insert documents into a MongoDB database.

insertOne()
To insert a single document, use the insertOne() method.

This method inserts a single object into the database.

Note: When typing in the shell, after opening an object with curly braces "{"
you can press enter to start a new line in the editor without executing the
command. The command will execute when you press enter after closing the
braces.

Example
db.posts.insertOne({
title:"Post Title 1",

body:"Body of post.",

category:"News",

likes:1,

tags:["news","events"],

date:Date()

})

Note: If you try to insert documents into a collection that does not exist,
MongoDB will create the collection automatically.

insertMany()
To insert multiple documents at once, use the insertMany() method.

This method inserts an array of objects into the database.

Example
db.posts.insertMany([

title:"Post Title 2",

body:"Body of post.",

category:"Event",

likes:2,

tags:["news","events"],

date:Date()

},

title:"Post Title 3",

body:"Body of post.",

category:"Technology",

likes:3,

tags:["news","events"],
date:Date()

},

title:"Post Title 4",

body:"Body of post.",

category:"Event",

likes:4,

tags:["news","events"],

date:Date()

])

MongoDB mongosh Find


Find Data
Find Data
There are 2 methods to find and select data from a MongoDB
collection, find() and findOne().

find()
To select data from a collection in MongoDB, we can use the find() method.

This method accepts a query object. If left empty, all documents will be
returned.

Example
db.posts.find()

findOne()
To select only one document, we can use the findOne() method.
This method accepts a query object. If left empty, it will return the first
document it finds.

Note: This method only returns the first match it finds.

Example
db.posts.findOne()

Querying Data
To query, or filter, data we can include a query in
our find() or findOne() methods.

Example
db.posts.find({category:"News"})

Projection
Both find methods accept a second parameter called projection.

This parameter is an object that describes which fields to include in the results.

Note: This parameter is optional. If omitted, all fields will be included in the
results.

Example
This example will only display the title and date fields in the results.

db.posts.find({},{title:1, date:1})

Notice that the _id field is also included. This field is always included unless
specifically excluded.

We use a 1 to include a field and 0 to exclude a field.


Example
This time, let's exclude the _id field.

db.posts.find({},{_id:0, title:1, date:1})

Note: You cannot use both 0 and 1 in the same object. The only exception is
the _id field. You should either specify the fields you would like to include or the
fields you would like to exclude.

Let's exclude the date category field. All other fields will be included in the
results.

Example
db.posts.find({},{category:0})

We will get an error if we try to specify both 0 and 1 in the same object.

Example
db.posts.find({},{title:1, date:0})

MongoDB mongosh Update


Update Document
To update an existing document we can use
the updateOne() or updateMany() methods.

The first parameter is a query object to define which document or documents


should be updated.

The second parameter is an object defining the updated data.


updateOne()
The updateOne() method will update the first document that is found matching
the provided query.

Let's see what the "like" count for the post with the title of "Post Title 1":

Example
db.posts.find({ title:"Post Title 1"})

Now let's update the "likes" on this post to 2. To do this, we need to use
the $set operator.

Example
db.posts.updateOne({ title:"Post Title 1"},{ $set:{ likes:2}})

Check the document again and you'll see that the "like" have been updated.

Example
db.posts.find({ title:"Post Title 1"})

Insert if not found


If you would like to insert the document if it is not found, you can use
the upsert option.

Example
Update the document, but if not found insert it:

db.posts.updateOne(

{ title:"Post Title 5"},

$set:
{

title:"Post Title 5",

body:"Body of post.",

category:"Event",

likes:5,

tags:["news","events"],

date:Date()

},

{upsert:true}

updateMany()
The updateMany() method will update all documents that match the provided
query.

Example
Update likes on all documents by 1. For this we will use the $inc (increment)
operator:

db.posts.updateMany({},{ $inc:{ likes:1}})

Now check the likes in all of the documents and you will see that they have all
been incremented by 1.

MongoDB mongosh Delete


Delete Documents
We can delete documents by using the methods deleteOne() or deleteMany().

These methods accept a query object. The matching documents will be deleted.
deleteOne()
The deleteOne() method will delete the first document that matches the query
provided.

Example
db.posts.deleteOne({ title:"Post Title 5"})

deleteMany()
The deleteMany() method will delete all documents that match the query
provided.

Example
db.posts.deleteMany({ category:"Technology"})

You might also like