0% found this document useful (0 votes)
7 views31 pages

UE20MC505B_Unit2_LectureNotes

Uploaded by

sreenu_pes
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 views31 pages

UE20MC505B_Unit2_LectureNotes

Uploaded by

sreenu_pes
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/ 31

Query and Projection Operators | Dr.

Lekha A

Query Operators

Operators

 Comparison  Logical  Element

 Evaluation  Geospatial  Array

 Bitwise  Projection

Comparison Operators

Name Description

$eq Matches values that are equal to a specified value.

{field: {$eq: value}}

$gt Matches values that are greater than a specified value.

{field: {$gt: value}}

pg. 1
Query and Projection Operators | Dr. Lekha A

$gte Matches values that are greater than or equal to a specified value.

{field: {$gte: value}}

$in Matches any of the values specified in an array.

{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }

$lt Matches values that are less than a specified value.


{field: {$lt: value}}

pg. 2
Query and Projection Operators | Dr. Lekha A

$lte Matches values that are less than or equal to a specified value.
{field: {$lte: value}}

$ne Matches all values that are not equal to a specified value.
{field: {$ne: value}}

$nin Matches none of the values specified in an array.

pg. 3
Query and Projection Operators | Dr. Lekha A

{ field: { $nin: [ <value1>, <value2> ... <valueN> ]} }

Logical Query Operators

Operator Description
$and Joins query clauses with a logical AND returns all documents that match
the conditions of both clauses.

$not Inverts the effect of a query expression and returns documents that do
not match the query expression

$nor Joins query clauses with a logical NOR returns all documents that fail to
match both clauses

pg. 4
Query and Projection Operators | Dr. Lekha A

$or Joins query clauses with a logical OR returns all documents that match
the conditions of either clause

Element query operators

Operator Description
$exists Matches documents that have the specified field

$type Selects documents if a field is of the specified type

pg. 5
Query and Projection Operators | Dr. Lekha A

Evaluation Query Operators

Operator Description
$expr Allows use of aggregation expressions within the query language

$mod Performs a modulo operation on the value of a field and selects


documents with a specified result

Array Query Operators

Operator Description
$all Matches arrays that contain all elements specified in the query.
{ <field>: { $all: [ <value1> , <value2> ... ] } }

pg. 6
Query and Projection Operators | Dr. Lekha A

$elemMatch Selects documents if element in the array field matches all the specified
$elemMatch conditions.
{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }

pg. 7
Query and Projection Operators | Dr. Lekha A

Bitwise query operator

Operator Description
Matches numeric or binary values in which a set of bit positions all
$bitsAllClear
have a value of 0
$bitsAllSet Matches numeric or binary values in which a set of bit positions all
have a value of 1
$bitsAnyClear Matches numeric or binary values in which any bit from a set of bit
positions has a value of 0
Matches numeric or binary values in which any bit from a set of bit
$bitsAnySet
positions has a value of 1

Projection Query Operators

Operator Description
$ The positional $ operator limits the contents of an <array> to return
either:
 The first element that matches the query condition on the
array.

pg. 8
Query and Projection Operators | Dr. Lekha A

 The first element if no query condition is specified for the array


(in MongoDB 4.4)
{ "<array>.$" : value }

It also works on embedded arrays

pg. 9
Query and Projection Operators | Dr. Lekha A

Update Operators

Operator Description
$currentDate Sets the value of a field to current date, either as a Date or a
Timestamp.
{ $currentDate: { <field1>: <typeSpecification1>, ... } }
<typeSpecification> can be either
a boolean true to set the field value to the current date as a Date,
or
document { $type: "timestamp" } or { $type: "date" } which
explicitly specifies the type
The operator is case-sensitive and accepts only the
lowercase "timestamp” or the lowercase "date"

$inc Increments the value of the field by the specified amount.


{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
The $inc operator accepts positive and negative values.
If the field does not exist, $inc creates the field and sets the field to
the specified value.
Use of the $inc operator on a field with a null value will generate an
error.
$inc is an atomic operation within a single document.

pg. 10
Query and Projection Operators | Dr. Lekha A

$min Only updates the field if the specified value is less than the existing
field value.
{ $min: { <field1>: <value1>, ... } }
If the field does not exists, the $min operator sets the field to the
specified value.
For comparisons between values of different types, such as a
number and a null, $min uses the BSON comparison order.

pg. 11
Query and Projection Operators | Dr. Lekha A

$max Only updates the field if the specified value is greater than the
existing field value.
{ $max: { <field1>: <value1>, ... } }
The $max operator updates the value of the field to a specified
value if the specified value is greater than the current value of the
field.
The $max operator can compare values of different types, using
the BSON comparison order.

$mul Multiplies the value of the field by the specified amount.


{ $mul: { field: <number> } }
If the field does not exist in a document, $mul creates the field and
sets the value to zero of the same numeric type as the multiplier.

pg. 12
Query and Projection Operators | Dr. Lekha A

$set Sets the value of a field in a document.


{ $set: { <field1>: <value1>, ... } }
If the field does not exist, $set will add a new field with the specified
value, provided that the new field does not violate a type constraint.

$setOnInsert Sets the value of a field if an update results in an insert of a


document.
Has no effect on update operations that modify existing documents.
{ $setOnInsert: { <field1>: <value1>, ... } }

pg. 13
Query and Projection Operators | Dr. Lekha A

$unset Removes the specified field from a document.


{ $unset: { <field1>: "", ... } }
If the field does not exist, then $unset does nothing (i.e. no
operation).

$addToSet The $addToSet operator adds a value to an array unless the value
is already present, in which case $addToSet does nothing to that
array.
{ $addToSet: { <field1>: <value1>, ... } }

pg. 14
Query and Projection Operators | Dr. Lekha A

Array Operators

Operator Description
$[] The all positional operator $[] indicates that the update operator
should modify all elements in the specified array field.
{ <update operator>: { "<array>.$[]" : value } }

$[<identifier>] The filtered positional operator $[<identifier>] identifies the array


elements that match the arrayFilters conditions for an update
operation.
{ <update operator>: { "<array>.$[<identifier>]" : value } },
{ arrayFilters: [ { <identifier>: <condition> } } ] }

pg. 15
Query and Projection Operators | Dr. Lekha A

$pop The $pop operator removes the first or last element of an array.
Pass $pop a value of -1 to remove the first element of an array and
1 to remove the last element in an array.
{ $pop: { <field>: <-1 | 1>, ... } }

$push The $push operator appends a specified value to an array.


{ $push: { <field1>: <value1>, ... } }

pg. 16
Query and Projection Operators | Dr. Lekha A

$pull The $pull operator removes from an existing array all instances of a
value or values that match a specified condition.
{ $pull: { <field1>: <value|condition>, <field2>:
<value|condition>, ... } }

$pullAll The $pullAll operator removes all instances of the specified values
from an existing array.
Unlike the $pull operator that removes elements by specifying a
query, $pullAll removes elements that match the listed values.
{ $pullAll: { <field1>: [ <value1>, <value2> ... ], ... } }.

pg. 17
Query and Projection Operators | Dr. Lekha A

Modifiers

Operator Description
$each The $each modifier is available for use with the $addToSet operator
and the $push operator.
Use with the $addToSet operator to add multiple values to an array
<field> if the values do not exist in the <field>.
{ $addToSet: { <field>: { $each: [ <value1>, <value2> ... ] } } }
Use with the $push operator to append multiple values to an array
<field>.
{ $push: { <field>: { $each: [ <value1>, <value2> ... ] } } }

pg. 18
Query and Projection Operators | Dr. Lekha A

$position The $position modifier specifies the location in the array at which
the $push operator inserts elements. Without the $position modifier,
the $push operator inserts elements to the end of the array.
To use the $position modifier, it must appear with the $each
modifier.

$slice The $slice modifier limits the number of array elements during a
$push operation.
To use the $slice modifier, it must appear with the $each modifier.
Can pass an empty array [] to the $each modifier such that only the
$slice modifier has an effect.

$sort The $sort modifier orders the elements of an array during a $push
operation.
To use the $sort modifier, it must appear with the $each modifier.

pg. 19
Query and Projection Operators | Dr. Lekha A

Find Variations

 Returns a limit of documents that satisfy a query.

 db.<collection_name>.find(query,options).limit(<number>)

 Skipping the first set of documents.

 db.<collection_name>.find().skip(<number>)

pg. 20
Query and Projection Operators | Dr. Lekha A

 To skip a few documents and limit the number.

 db.<collection>.find().skip(N).limit(M)

 To display last records.

 db.<collection>.find().skip(db.<collection>.count() – N)

 To display in reverse order

 db.collection.find().sort({ $natural: -1 }).limit(N)

pg. 21
Query and Projection Operators | Dr. Lekha A

 Returns one document that satisfies the specified query criteria on the collection.

 db.<collection_name>.findOne(query, projection)

 If multiple documents satisfy the query, this method returns the first document
according to the natural order which reflects the order of documents on the disk.
 In capped collections, natural order is the same as insertion order.
 If no document satisfies the query, the method returns null.
 Returns a single document without any query.

 db.<collection_name>.findOne()

 Modify and return a single document.

 db.collection.findAndModify({

pg. 22
Query and Projection Operators | Dr. Lekha A

 query: <document>, sort: <document>,

 remove: <boolean>,

 update: <document or aggregation pipeline>

 new: <boolean>, fields: <document>, upsert: <boolean>,

 bypassDocumentValidation: <boolean>,

 writeConcern: <document>, collation: <document>,

 arrayFilters: [ <filterdocument1>, ... ]

 })

pg. 23
Query and Projection Operators | Dr. Lekha A

 Deletes a single document based on the filter and sort criteria, returning the deleted
document.

 db.collection.findOneAndDelete(

 <filter>, {

 projection: <document>, sort: <document>,

 maxTimeMS: <number>, collation: <document> } )

pg. 24
Query and Projection Operators | Dr. Lekha A

 Replaces a single document based on the specified filter.

 db.collection.findOneAndReplace(

 <filter>,

 <replacement>,

 {projection: <document>, sort: <document>,

 maxTimeMS: <number>, upsert: <boolean>,

 returnNewDocument: <boolean>})

pg. 25
Query and Projection Operators | Dr. Lekha A

 Updates a single document based on the filter and sort criteria.

 db.collection.findOneAndUpdate(

 <filter>, <update document or aggregation pipeline>, {

 projection: <document>, sort: <document>,

 maxTimeMS: <number>, upsert: <boolean>,

 returnNewDocument: <boolean>,

 arrayFilters: [ <filterdocument1>, ... ] })

pg. 26
Query and Projection Operators | Dr. Lekha A

Update Variations

 Replace a single document within the collection based on the filter.

 db.<collection_name>.replaceOne(<filter>, <replacement>)

 In a capped collection if a replacement operation changes the document size,


the operation will fail.

pg. 27
Query and Projection Operators | Dr. Lekha A

 Updates a single document within the collection based on the filter.

 db.<collection_name>.updateOne(filter, update, options)

 In a capped collection if a update operation changes the document size, the


operation will fail.

 Updates multiple documents within the collection based on the filter.

 db.<collection_name>.updateMany(filter, update, options)

 In a capped collection if a update operation changes the document size, the


operation will fail.

pg. 28
Query and Projection Operators | Dr. Lekha A

 Removes a single document from a collection.

 db.<collection_name>.deleteOne(filter, options)

 Removes multiple documents from a collection.

 db.<collection_name>.deleteMany(filter, options)

Collection Methods

Distinct

 Finds the distinct values for a specified field across a single collection or view and return
the results in an array.

 db.<collection_name>.distinct(field, query, options)

 Distinct with embedded documents

pg. 29
Query and Projection Operators | Dr. Lekha A

Count

 Returns the count of documents that would match a find() query for the collection or
view.

 db.<collection_name>.count(query, options)

 The db.<collection_name>.count() method does not perform the find() operation


but instead counts and returns the number of results that match a query.
 The options can be
 limit – the maximum number of documents to count

 skip – the number of documents to skip before counting

 hint – an index name hint

 maxTimeMS – the maximum amount of time to allow the query to run

Count Documents

 Returns the count of documents that match the query for a collection or view.

 db.collection.countDocuments(query, options)

pg. 30
Query and Projection Operators | Dr. Lekha A

pg. 31
Copy protected with Online-PDF-No-Copy.com

You might also like