mongoDB - 2 LIMIT and SELECTORS

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

INTRODUCTION

What is MongoDB?
MongoDB is a source-available, cross-platform, document-oriented
database program.
Classified as a NoSQL database product, MongoDB utilizes JSON-like
documents with optional schemas .

What is database?

• A database is an organized collection of data stored in a computer


system and usually controlled by a database management system
(DBMS).
• The data in common databases is modeled in tables, making querying
and processing efficient.

Structured Data:

• Structured data refers to data that is organized and formatted in a


specific way to make it easily readable and understandable by both
humans and machines.
• This is typically achieved through the use of a well-defined schema
or data model, which provides a structure for the data.

Database Management System:

• A database management system (DBMS) is system software for


creating and managing databases.
• A DBMS makes it possible for end users to create, protect, read, update
and delete data in a database.
FEW COMMANDS TO TEST AFTER CONNECTIONS

show dbs:

It will display a list of all the available databases.

use db:

To create a database.

show collections:

It will show all the collections in the currently selected database.

db.collection.insert():
Inserts a document or documents into a collection.

db.collection.find():
Selects documents in a collection or view and returns a cursor to the
selected documents.

Document:

A document is a fundamental unit of data storage. It’s a record that


contains field-and-value pairs, similar to a JSON object.
The representation of a document varies by programming language,
but most languages have a data structure that is a natural fit, such as a
map, hash, or dictionary.
{"greeting" : "DATA SCIENCE"}

Collections:

A collection is a grouping of MongoDB documents.


Each document within a collection can have different fields.
They are analogous to tables in relational databases.

Database:

MongoDB groups collections into databases.

A single instance of MongoDB can host several databases, each


grouping together zero or more collections.

A database has its own permissions, and each database is stored in


separate files on disk.

A good rule of thumb is to store all data for a single application in the
same database.

Datatype:

Basically each document will be in JSON format which will be as


follows. Where each attributes inside can be of multiple data types

{
"name: Nanditha Naveen”,
“address”:{
“street”:”Jai Maruthi Nagar”,
“city”:”Chikmagalur”,
“state”:”Karnataka”
}}

WHERE, AND, OR & CRUD

WHERE

Given a Collection you want to FILTER a subset based on a condition.


That is the place WHERE is used.

db.students.find({ gpa: {$lt: 2.5}});

OUTPUT
OR
The $or operator is used to specify a compound query with multiple
conditions, where at least one condition must be satisfied for a document to
match.

db.students.find({$or:[{home_city:”City
4”},{gpa:{$gt:3.0}}]});

OUTPUT
AND
The $and operator allows you to specify multiple conditions that documents
must satisfy to match the query.

db.students.find({ $and: [{ is_hotel_resident:true} ,


{ home_city:"City 5"}]});

OUTPUT
CRUD

• C - Create / Insert
• R - Remove
• U - update
• D - Delete
This is applicable for a Collection (Table) or a Document (Row)
INSERT

• The insert() method in MongoDB inserts documents in the


MongoDB collection. This method is also used to create a new
collection by inserting documents.
• You can insert documents with or without the _id field. If you
insert a document in the collection without the _id field, then
MongoDB will automatically add an _id field and assign it with a
unique ObjectId.
And if you insert a document with the _id field, then the value
of the _id field must be unique to avoid the duplicate key error.

insertOne()

insertOne() method inserts a document into the collection. This


method inserts only one document at a time. This method can also be
used inside multi-document transactions.

const studentData = {

“name”: “John Doe”,

“age”: 24,

“courses”: ['Physics', 'Computer Science', 'Mathematics', 'History'],

“gpa”:4.5,

“home_city”:”New York”,

“blood_group”:”O+”,

“is_hotel_resident”:true

}:
UPDATE

• The update() method in MongoDB updates a document or


multiple documents in the collection. When the document is
updated the _id field remains unchanged.
• This method can be used for a single updating of
documents as well as multiple documents. By default, the
db.collection.update() method updates a single document.

UpdateOne()

• The updateOne() method in MongoDB updates the first matched


document within the collection based on the given query.
• The value of the _id field remains unchanged after updating the
value. This method updates one document at a time and can also
add new fields to the given document.

db.students.updateOne({ name: ‘John Doe’}, { $set:


{ gpa: 4.2 }});

OUTPUT:

UpdateMany()
• The updateMany() method updates all the documents in
MongoDB collections that match the given query. When you
update your document, the value of the _id field remains
unchanged.
• You can also use this method inside multi-document transactions.

db.students.updateMany({ gpa: { $lt: 4.0}},{$inc:


{gpa: 0.5}});

OUTPUT:

DeleteMany()

• The deleteMany() method is a part of MongoDB’s CRUD (Create,


Read, Update, and Delete) operations. As the name suggests, it is
used to delete more than one document that satisfies the specified
criteria.
• deleteMany() returns acknowledged as true if the function runs
with the writeConcern parameter; otherwise, false.

db.students.deleteMany({ is_hotel_resident: true});


OUTPUT:

PROJECTION

• MongoDB Projection is a special feature allowing you to select

only the necessary data rather than selecting the whole set of data

from the document.

• For Example, If a Document contains 10 fields and only 5 fields

are to be shown the same can be achieved using the Projections.

This enable us to:

• Project concise yet transparent data

• Filter data without impacting the overall database performance.

How Does MongoDB Projection Works?

• MongoDB projections are constructed on top of the existing


find() query and therefore making it easier to use without
significant modifications to the existing functions/queries.

• Moreover, projection plays a key factor when looking for user-


centric data from a given large data set.

EXAMPLE 1:
db.students.find({}, {_id: 1, gpa: 1});

OUTPUT

EXAMPLE 2 :

db.students.find({}, {name:1, home_city:1, _id:0});

OUTPUT
MongoDB Projection Operators

MongoDB projection method positively impacts database


performance as it reduces the workload of the find query when trying
to retrieve specific data from a document, minimizing resource usage.

To enhance the querying and reduce the workload, multiple operators

can be used within a projection query like the ones below:

• $slice

• $elemMatch

• $meta

1. $slice operator :
The $slice operator bounds the number of elements that should
be returned as the output of a MongoDB projection query.

Limitations in $slice operator:


• In a nested array the $slice operator will only return the sliced

element and will not return any other item, especially from

MongoDB 4.4.

• The find() action is not supported by the $slice operator on

MongoDB views.

• Due to a constraint imposed by MongoDB, the $slice operator

cannot be combined with the $ projection operator. This is

because top-level fields are not permitted to contain the $ symbol

as part of the field name.

EXAMPLE:

db.students.find({}, {name:1, age: {$slice:4}});

OUTPUT:
2. $elemMatch :
The $elemMatch operator also limits the contents of an array to

the first element that fits the given constraint. Though, there is a minor

difference from the $ operator because the $elemMatch projection

operator needs an explicit condition argument.

Limitations of $elemMatch operator are as follows:

• The field to which the $elemMatch projection is applied is

returned as the last field of the document, regardless of the order

in which the fields are ordered.

• $elemMatch projection operator is not supported by find()

operations on MongoDB views.

• The $elemMatch operator does not handle $text query

expressions.

EXAMPLE :

db.candidates.find({courses:
{$elemMatch:{$eq:"English"}}},{age:1,"courses.$":1})
;

OUTPUT:
BENEFITS OF PROJECTION:

1. Data Reduction: By specifying which fields to include or exclude,


you can reduce the amount of data sent to applications. This
optimization is crucial for bandwidth efficiency.

2. Performance Optimization: Limiting the fields returned can


improve query performance. Instead of retrieving all data, you
only fetch what’s necessary.

3. User-Centric Data: Projection helps extract specific fields relevant


to user needs from large datasets12. For example, you can select
only the name and age of employees rather than displaying all
details.
LIMIT

• The limit() method limits the number of records or documents that


you want. It basically defines the max limit of records/documents
that you want.

• Or in other words, this method uses on cursor to specify the


maximum number of documents/ records the cursor will return.

• We can use this method after the find() method and find() will give
you all the records or documents in the collection. You can also
use some conditions inside the find to give you the result that you
want.

Syntax:

db.collectionName.find(<query>).limit(<number>)

EXAMPLE 1:

db.candidates.find({}, {_id:0}).limit(3);
OUTPUT:

EXAMPLE 2:

db.candidates.find({gpa: {$gt:2.5}} , {_id:1}).limit(3);


OUTPUT

Use of 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.
• We can use the limit() method with the sort() method, it will return
the first m documents, where m is the given limit.

EXAMPLE 3:

db.candidates.find({}, { _id:1}).sort({_id:-1}).limit(4);
OUTPUT
SELECTORS

Comparison gt lt:

db.candidates.find({ age: { $gt: 10}});

OUTPUT

db.candidates.find({age: {$lt: 25}});


OUTPUT:
BITWISE TYPES:

$bitsAllClear :
It matches documents where all the locations of bits specified in
the query are clear—0.

$bitsAllSet :
It matches documents where all the locations of bits specified in
the query are set—1.

$bitsAnyClear :

It matches documents where any location of bits specified in the


query are clear—0.

$bitsAnySet :

It matches documents where any location of bits specified in the


query are set—1.
QUERY

You can query documents in MongoDB by using the following


methods:

• Your programming language's driver.

• The MongoDB Atlas UI. To learn more, see Query Documents with

MongoDB Atlas.

• MongoDB Compass.

GEOSPATIAL QUERY :

MongoDB offers a rich set of geospatial query operators,

including $geoNear, $geoWithin, $geoIntersects, and $nearSphere.

These operators enable developers to perform complex geospatial

queries, such as finding points within a specified radius, identifying

polygons that intersect with a given area, or searching for locations

based on proximity.

EXAMPLE :

db.locations.find({ location: { $geoWithin:


{ $centerSphere: [[ -72.004, 42.712], 0.00723167]}}});

DATA TYPES AND OPERATIONS


$geoIntersects :
Selects documents whose geospatial data intersects with a
specified GeoJSON object; i.e. where the intersection of the data and
the specified object is non-empty.

$geoWithin :
Selects documents with geospatial data that exists entirely within a
specified shape.

$near :
Specifies a point for which a geospatial query returns the
documents from nearest to farthest. The $near operator can specify
either a GeoJSON point or legacy coordinate point.

$nearSphere :
Specifies a point for which a geospatial query returns the
documents from nearest to farthest. $nearSphere requires a geospatial
index.

You might also like