KEMBAR78
Query Lectures | PDF | Information Retrieval | Mongo Db
0% found this document useful (0 votes)
7 views20 pages

Query Lectures

The document outlines CRUD (Create, Read, Update, Delete) methods in MongoDB, detailing specific commands for each operation. It also explains various query operators for comparison and logical operations, as well as aggregation features for data processing. Additionally, it includes examples of using aggregation pipelines, stages, and single-purpose aggregation methods.
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)
7 views20 pages

Query Lectures

The document outlines CRUD (Create, Read, Update, Delete) methods in MongoDB, detailing specific commands for each operation. It also explains various query operators for comparison and logical operations, as well as aggregation features for data processing. Additionally, it includes examples of using aggregation pipelines, stages, and single-purpose aggregation methods.
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/ 20

CRUD Methods

Create
Method Description

db.collection.insertOne(doc) Insert a single document

db.collection.insertMany([docs]) Insert multiple documents

Read
Method Description

find(query) Find all documents that match the query

findOne(query) Find a single document

find().count() Count matching documents

Update
Method Description

updateOne(filter, update) Update a single document

updateMany(filter, update) Update multiple documents

replaceOne(filter, replacement) Replace one document entirely

Delete
Method Description

deleteOne() Delete one document

deleteMany() Delete multiple documents


MongoDB Query Operators
Query

• Query is a request for data or information from a database.


• Query is a statement used to retrieve, insert, update, or delete data stored in a database.

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

Write commands on cmd

Enter int data in mongodb


},
"name": "Bob",
"class":"BBA",
"age": {
"$numberInt": "19"
}}
Command:

mongosh = mongodb shell

show dbs

Use database_name (students)

show collections

db.data.find()
COMPARISON OPERATORS
db.data.find({age:"25"})

db.data.find({age: {$eq:25}})

db.data.find({age: {$ne:25}})
shows that which doesnot have age 25 ….less than 25
db.data.find({class: {$ne:"BBA"}})

Update data using query


db.data.updateMany({age:{$lt:20}},{$set:{class:"ARTS"}});
Delete data using query
We don’t need second parameter class in order to del entries
db.data.deleteMany({age:{$lt:20}});

LOGICAL QUERY OPERATORS


In order to pass multiple conditions use curly brackets

It fetchs the in between age


db.data.find({$and: [
{age:{$gt:19}},
{age:{$lt:25}}
]});
db.data.find({$and:[{age:{$gt:19}},{age:{$lt:29}}]},{name:1,age:1,class:1,_i
d:0});
don’t want to use id then use this command

db.data.find({$and:[{age:{$gt:19}},{class:{$eq:”BBA”}}]},{name:1,age:1,clas
s:1,_id:0});
AGGREGATION
Aggregation is a powerful feature in MongoDB that allows you to perform data
processing and transformation like GROUP BY, JOIN, SUM, COUNT, FILTER, and more —
all using a pipeline of stages.

Document 1 Document 1 Document 1 Document 1

Stage

Document 1 Document 1 Document 1


PIPELINE

Stage

Document 1
$match
$count
$sort
$Project
$Limit
$group
Run an Aggregation Pipeline

To run an aggregation pipeline, use:

• db.collection.aggregate()
Aggregation Operations

Aggregation operations process multiple documents and return computed results. You can use
aggregation operations to:

• Group values from multiple documents together.

• Perform operations on the grouped data to return a single result.

• Analyze data changes over time.

Aggregation Pipelines

An aggregation pipeline consists of one or more stages that process documents:

• Each stage performs an operation on the input documents. For example, a stage can filter
documents, group documents, and calculate values.

• The documents that are output from a stage are passed to the next stage.

• An aggregation pipeline can return results for groups of documents. For example, return
the total, average, maximum, and minimum values.

Aggregation Pipeline Example

The following aggregation pipeline example contains two stages and returns the total
order quantity of medium size pizzas grouped by pizza name:

db.orders.aggregate( [

// Stage 1: Filter pizza order documents by pizza size


{ $match: { size: "medium" }},

// Stage 2: Group remaining documents by pizza name and calculate total quantity

{ $group: { _id: "$name", totalQuantity: { $sum: "$quantity" } }

}])

The $match stage:

• Filters the pizza order documents to pizzas with a size of medium .

• Passes the remaining documents to the $group stage.

The $group stage:

• Groups the remaining documents by pizza name .

• Uses $sum to calculate the total order quantity for each pizza name . The total is
stored in the totalQuantity field returned by the aggregation pipeline.

db.listingsAndReviews.aggregate(

[ { $group : { _id : "$property_type" } } ])

The $sort stage:

• Sorts the documents by the total order value for each group in descending order
( -1 ).

• Returns the sorted documents.

db.listingsAndReviews.aggregate([

{
$sort: { "accommodates": -1 }

}, {

$project: {

"name": 1,

"accommodates": 1}},

Aggregation $project
This aggregation stage passes only the specified fields along to the next
aggregation stage.

This is the same projection that is used with the find() method.

db.restaurants.aggregate([

{ $project: {

"name": 1,

"cuisine": 1,

"address": 1}},

Aggregation $match
This aggregation stage behaves like a find. It will filter documents that match
the query provided.

Using $match early in the pipeline can improve performance since it limits the
number of documents the next stages must process.

db.listingsAndReviews.aggregate([
{ $match : { property_type : "House" } },

{ $limit: 2 },

{ $project: {

"name": 1,

"bedrooms": 1,

"price": 1

}}

])

Aggregation $lookup
This aggregation stage performs a left outer join to a collection in the same
database.

There are four required fields:

• from: The collection to use for lookup in the same database


• localField: The field in the primary collection that can be used as a unique
identifier in the from collection.
• foreignField: The field in the from collection that can be used as a unique
identifier in the primary collection.
• as: The name of the new field that will contain the matching documents
from the from collection.

db.comments.aggregate([

$lookup: {

from: "movies",

localField: "movie_id",

foreignField: "_id",
as: "movie_details", },

}, {$limit: 1}])

Aggregation $out
This aggregation stage writes the returned documents from the aggregation
pipeline to a collection.

The $out stage must be the last stage of the aggregation pipeline.

db.listingsAndReviews.aggregate([

$group: {

_id: "$property_type",

properties: {

$push: {

name: "$name",

accommodates: "$accommodates",

price: "$price",

},

},

},

},

{ $out: "properties_by_type" },

])
Single Purpose Aggregation Methods

The single purpose aggregation methods aggregate documents from a


single collection. The methods are simple but lack the capabilities of an
aggregation pipeline.
Method Description
db.collection.estimatedDocumentCount() Returns an approximate count of the
documents in a collection or a view.

db.collection.count() Returns a count of the number of


documents in a collection or a view.

db.collection.distinct() Returns an array of documents that


have distinct values for the specified
field.

Db.data.

Pipeline Stages

Stage Purpose
$match Filter documents
$group Group and aggregate data
$sort Sort documents
$project Reshape documents (select fields)
$limit Limit number of documents
$lookup Perform JOIN with another collection
db.data.aggregate([
{$match: { age: { $gt:25 }}},
{$sort:{ age:1 }}, //ascending order
{$project: {name:1,class:0}} //find particular fileds
])
Match Operator:
db.data.aggregate([
{$match: {age:25}}
])

db.data.aggregate([
{$match: {age:{$gt:25}}}
])
db.data.aggregate([
{$match: {$and:[
{age:{$gt: 20}},
{class:”BBA”}
]}}
])

db.data.aggregate([{$match:{age:{$gt:19}}},{$count:"name"}])

Using SORT
Sort=1 //ascending order
Sort=-1 //descending order
db.data.aggregate([{$match:{age:{$gt:19}}},{$sort:{age:1}}])
PROJECT operator
db.data.aggregate([{$match:{age:{$gt:19}}},{$sort:{age:1,name:1}},{$project:{name:1,class:1,_id
:0}}])

Group operator
Want to group the documents
Class:BBA
Class: computer Science
Basic Syntax of $group
db.collection.aggregate([
{
$group: {
_id: <expression>, // Grouping key
<field1>: { <accumulator>: <expression> },
<field2>: { <accumulator>: <expression> },
...
}
}
])

MongoDB Operators
Operator Description
$sum Calculates the sum of numeric values.
$avg Calculates the average of numeric values.
$min Returns the minimum value.
$max Returns the maximum value.
$first Returns the first value in the group (based on document order).
$last Returns the last value in the group (based on document order).
$push Appends values to an array (duplicates allowed).
$addToSet Appends unique values to an array (no duplicates).
$stdDevPop Calculates population standard deviation of numeric values.
$stdDevSamp Calculates sample standard deviation of numeric values.
$count Counts the number of documents in the group (MongoDB 5.0+).
$mergeObjects Merges documents into a single document (MongoDB 4.2+).
$accumulator Defines a custom accumulator in JavaScript (MongoDB 5.0+).

db.data.aggregate([{$group:{_id:"$class"}}])

Find total number of students


db.data.aggregate([{$group:{_id:"$class", count:{$sum:1}}}])
LOOKUP OPEARTOR
Definition of $lookup
$lookup lets you join documents from two collections, similar to an SQL JOIN. It brings in
matching documents from a “foreign” collection based on a specified condition.
{
$lookup: {
from: "<foreignCollection>", // Name of the other collection
localField: "<localField>", // Field from the current collection
foreignField: "<foreignField>", // Field from the foreign collection
as: "<outputArrayField>" // Name of the array field to store results
}
}

Example
db. Restaurent .aggreagate{
$lookup: {
from: “user” // Name of the other collection
localField: "id", // Field from the current collection
foreignField: "Section", // Field from the foreign collection
as: "Restaurent " // Name of the array field to store results
}
}

You might also like