Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

WT Unit-4 Mongo DB

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

MongoDB

MongoDB is a document database and can be installed locally or hosted in the


cloud.

SQL vs Document Databases


SQL databases are considered relational databases. They store related data in
separate tables. When data is needed, it is queried from multiple tables to join
the data back together.

MongoDB is a document database which is often referred to as a non-relational


database. This does not mean that relational data cannot be stored in document
databases. It means that relational data is stored differently. A better way to
refer to it is as a non-tabular database.

MongoDB stores data in flexible documents. Instead of having multiple tables


you can simply keep all of your related data together. This makes reading your
data very fast.

You can still have multiple groups of data too. In MongoDB, instead of tables
these are called collections.

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.

db.posts.insertOne({
title: "Post Title 1",
body: "Body of post.",
category: "News",
likes: 1,
tags: ["news", "events"],
date: Date()
})

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

This method inserts an array of objects into the database.

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()
}
])

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.

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.

db.posts.findOne()

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":

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.
db.posts.updateOne( { title: "Post Title 1" }, { $set: { likes: 2 }
} )

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

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 } })

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" })
MongoDB Query Operators
There are many query operators that can be used to compare and reference
document fields.

Comparison
The following operators can be used in queries to compare values:

 $eq: Values are equal


 $ne: Values are not equal
 $gt: Value is greater than another value
 $gte: Value is greater than or equal to another value
 $lt: Value is less than another value
 $lte: Value is less than or equal to another value
 $in: Value is matched within an array

Logical
The following operators can logically compare multiple queries.

 $and: Returns documents where both queries match


 $or: Returns documents where either query matches
 $nor: Returns documents where both queries fail to match
 $not: Returns documents where the query does not match

Evaluation
The following operators assist in evaluating documents.

 $regex: Allows the use of regular expressions when evaluating field


values
 $text: Performs a text search
 $where: Uses a JavaScript expression to match documents
Use a View to Join Two Collections

You can use $lookup to create a view over two collections and then run queries against
the view. Applications can query the view without having to construct or maintain
complex pipelines.

Example

Create two sample collections, inventory and orders :


db.inventory.insertMany( [

{ prodId: 100, price: 20, quantity: 125 },

{ prodId: 101, price: 10, quantity: 234 },

{ prodId: 102, price: 15, quantity: 432 },

{ prodId: 103, price: 17, quantity: 320 }

])

db.orders.insertMany( [

{ orderId: 201, custid: 301, prodId: 100, numPurchased:


20 },

{ orderId: 202, custid: 302, prodId: 101, numPurchased:


10 },

{ orderId: 203, custid: 303, prodId: 102, numPurchased: 5 },

{ orderId: 204, custid: 303, prodId: 103, numPurchased:


15 },

{ orderId: 205, custid: 303, prodId: 103, numPurchased:


20 },

{ orderId: 206, custid: 302, prodId: 102, numPurchased: 1 },


{ orderId: 207, custid: 302, prodId: 101, numPurchased: 5 },

{ orderId: 208, custid: 301, prodId: 100, numPurchased:


10 },

{ orderId: 209, custid: 303, prodId: 103, numPurchased: 30 }

])

Create a Joined View

This command uses db.createView() to create a new view named sales based on
the orders collection:
db.createView( "sales", "orders", [

$lookup:

from: "inventory",

localField: "prodId",

foreignField: "prodId",

as: "inventoryDocs"

},

$project:

_id: 0,

prodId: 1,

orderId: 1,

numPurchased: 1,
price: "$inventoryDocs.price"

},

{ $unwind: "$price" }

])

In the example:

 The $lookup stage uses the prodId field in the orders collection to "join"
documents in the inventory collection that have matching prodId fields.

 The matching documents are added as an array in the inventoryDocs field.

 The $project stage selects a subset of the available fields.

 The $unwind stage converts the price field from an array to a scalar value.

The documents in the sales view are:

{ orderId: 201, prodId: 100, numPurchased: 20, price: 20 },

{ orderId: 202, prodId: 101, numPurchased: 10, price: 10 },

{ orderId: 203, prodId: 102, numPurchased: 5, price: 15 },

{ orderId: 204, prodId: 103, numPurchased: 15, price: 17 },

{ orderId: 205, prodId: 103, numPurchased: 20, price: 17 },

{ orderId: 206, prodId: 102, numPurchased: 1, price: 15 },

{ orderId: 207, prodId: 101, numPurchased: 5, price: 10 },

{ orderId: 208, prodId: 100, numPurchased: 10, price: 20 },

{ orderId: 209, prodId: 103, numPurchased: 30, price: 17 }


MongoDB – sort() Method


In MongoDB, the sort() method is used to specify the order in which


the query returns matching documents from a collection. It allows
users to arrange documents in either ascending (1)
or descending (-1) order based on the values of one or more fields.
In this article, We will learn about the MongoDB sort() method in
detail by understanding the various examples and so on.
MongoDB sort()
 The sort() method in MongoDB is used to specify the order in
which the query returns matching documents from a given
collection. It must be applied to the cursor before retrieving any
documents from the database.
 It takes a document as a parameter that contains a field:
value pair that defines the sort order of the result set. The value
is 1 or -1 specifying an ascending or descending sort
respectively.

 If a sort returns the same result every time we perform on the


same data, then such type of sort is known as a stable sort.
 If a sort returns a different result every time we perform on the
same data, then such type of sort is known as unstable sort.

 MongoDB generally performs a stable sort unless sorting on a


field that holds duplicate values.
 We can use the limit() method with the sort() method, it will
return the first m documents, where m is the given limit.
 MongoDB can find the result of the sort operation using indexes.
 If MongoDB does not find sort order using index scanning, then it
uses the top-k sort algorithm.
Syntax:
db.Collection_Name.sort({field_name:1 or -1})
Explanation: This query sorts the documents
in Collection_Name by field_name in ascending order and -1 for
descending order.
Sorting data in MongoDB makes it easier to organize query
results. For a deeper understanding of data manipulation and
sorting in full-stack projects, the Full Stack Development with
Node JS course covers how to implement and optimize queries
with MongoDB.
Behavior of Sort method in MongoDB
 In MongoDB, the sort() method is used to sort the results of a
query in either ascending or descending order based on one or
more fields.
 The sort() method takes an object as an argument, where each
field to sort by is a key and the value is
either 1 for ascending order or -1 for descending order.
Here’s a basic example of using the sort() method:
db.collection.find().sort({ field1: 1, field2: -1 })
Explanation:
 In this example, the find() method retrieves documents from the
collection, and the sort() method sorts the results first by field1 in
ascending order, and then by field2 in descending order.
 If the sort() method is not provided, MongoDB will return the
documents in the order they are stored in the database, which is
typically the order in which they were inserted.
 It’s important to note that the sort() method can impact
performance, especially when sorting large result sets. In such
cases, it’s recommended to use indexes to improve the
performance of sorting operations.

Example 1: Ascending Order

db.student.find().sort({age:1})
Output:
[
{ _id: ObjectId('600f1abb923681e7681ebdcf'), name: 'Bablu',
age: 18 },
{
_id: ObjectId('600f1abb923681e7681ebdce'),
name: 'Akshay',
age: 19
},
{
_id: ObjectId('600f1abb923681e7681ebdd1'),
name: 'Gourav',
age: 20
},
{
_id: ObjectId('600f1abb923681e7681ebdd0'),
name: 'Rakesh',
age: 21
}
]

Example 2: Descending Order


db.student.find().sort({age:-1})
Output:
[
{
_id: ObjectId('600f1abb923681e7681ebdd0'),
name: 'Rakesh',
age: 21
},
{
_id: ObjectId('600f1abb923681e7681ebdd1'),
name: 'Gourav',
age: 20
},
{
_id: ObjectId('600f1abb923681e7681ebdce'),
name: 'Akshay',
age: 19
},
{ _id: ObjectId('600f1abb923681e7681ebdcf'), name: 'Bablu',
age: 18 }
]
Example 3: Ascending order of student name:
db.student.find().sort({name:1})
Output:
[
{
_id: ObjectId('600f1abb923681e7681ebdce'),
name: 'Akshay',
age: 19
},
{ _id: ObjectId('600f1abb923681e7681ebdcf'), name: 'Bablu',
age: 18 },
{
_id: ObjectId('600f1abb923681e7681ebdd1'),
name: 'Gourav',
age: 20
},
{
_id: ObjectId('600f1abb923681e7681ebdd0'),
name: 'Rakesh',
age: 21
}
]
Example 4: Descending order of student name::
db.student.find().sort({name:-1})
Output:
[
{
_id: ObjectId('600f1abb923681e7681ebdd0'),
name: 'Rakesh',
age: 21
},
{
_id: ObjectId('600f1abb923681e7681ebdd1'),
name: 'Gourav',
age: 20
},
{ _id: ObjectId('600f1abb923681e7681ebdcf'), name: 'Bablu',
age: 18 },
{
_id: ObjectId('600f1abb923681e7681ebdce'),
name: 'Akshay',
age: 19
}
]

You might also like