0% found this document useful (0 votes)
45 views63 pages

Mongodb Crud

Uploaded by

sahooabhijit5442
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)
45 views63 pages

Mongodb Crud

Uploaded by

sahooabhijit5442
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/ 63

Database For Big Data

Semester - 7th Course Code - CSE4252

MongoDB CRUD Operations

Department of Computer Science & Information Technology,


Faculty of Engineering and Technology,
Institute of Technical Education,
SIKSHA ’O’ ANUSANDHAN (Deemed to Be University),
Bhubaneswar, Odisha
Sudhanshu Shekhar Bisoyi Database For Big Data 1 / 62
Outline I

1 MongoDB CRUD Operations


Create or Insert Operation
Query Documents
Comparison Query operators
Logical Query operators
Element Query operators
Evaluation Query operators
Query operator Array
Query on Embedded/Nested Documents
Query on Nested Field
Query an Array
Specify Multiple Conditions for Array Elements
Project Fields to Return from Query
Query for Null or Missing Fields
Iterate a Cursor in mongosh
Update Documents
Update Documents in a Collection

Sudhanshu Shekhar Bisoyi Database For Big Data 2 / 62


MongoDB CRUD Operations

MongoDB CRUD Operations

MongoDB provides many CRUD operations create, read, update, and


delete.
Create Operations
Create or insert operations add new documents to a collection.
If the collection does not currently exist, insert operations will create
the collection.
MongoDB provides the following methods to insert documents into a
collection:
db.collection.insert()
db.collection.insertOne()
db.collection.insertMany()

Sudhanshu Shekhar Bisoyi Database For Big Data 3 / 62


MongoDB CRUD Operations

Read Operations
Read operations retrieve documents from a collection; i.e. query a
collection for documents.
MongoDB provides the following methods to read documents from a
collection:
db.collection.find()
You can specify query filters or criteria that identify the documents to
return.

Sudhanshu Shekhar Bisoyi Database For Big Data 4 / 62


MongoDB CRUD Operations

Update Operations
Update operations modify existing documents in a collection.
MongoDB provides the following methods to update documents of a
collection:
db.collection.updateOne() New in version 3.2
db.collection.updateMany() New in version 3.2
db.collection.replaceOne() New in version 3.2
In MongoDB, update operations target a single collection.
All write operations in MongoDB are atomic on the level of a single
document.
You can specify criteria, or filters, that identify the documents to
update.
These filters use the same syntax as read operations.

Sudhanshu Shekhar Bisoyi Database For Big Data 5 / 62


MongoDB CRUD Operations

Delete Operations
Delete operations remove documents from a collection.
MongoDB provides the following methods to delete documents of a
collection:
db.collection.deleteOne() New in version 3.2
db.collection.deleteMany() New in version 3.2
In MongoDB, delete operations target a single collection.
All write operations in MongoDB are atomic on the level of a single
document.
You can specify criteria, or filters, that identify the documents to
remove.
These filters use the same syntax as read operations.

Sudhanshu Shekhar Bisoyi Database For Big Data 6 / 62


MongoDB CRUD Operations Create or Insert Operation

Create or Insert Operation


Insert Single Document
db.collection.insertOne() inserts a single document into a collection.
The following example inserts a new document into the inventory
collection.
db.inventory.insertOne(
{
item: "canvas",
qty: 100,
tags: ["cotton"],
size: { h: 28, w: 35.5, uom: "cm" }
}
)

If the document does not specify an id field, MongoDB adds the id


field with an ObjectId value to the new document.
Sudhanshu Shekhar Bisoyi Database For Big Data 7 / 62
MongoDB CRUD Operations Create or Insert Operation

Insert Multiple Documents


db.collection.insertMany() can insert multiple documents into a
collection.
Pass an array of documents to the method. The following example
inserts three new documents into the inventory collection.
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size:
{ h: 14, w: 21, uom: "cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9,
w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"],
size: { h: 19, w: 22.85, uom: "cm" } }
])

If the documents do not specify an id field, MongoDB adds the id


field with an ObjectId value to each document.

Sudhanshu Shekhar Bisoyi Database For Big Data 8 / 62


MongoDB CRUD Operations Query Documents

Query Documents
Now we wil analyze the select queries using the db.collection.find()
method of mongoDB.
Selects documents in a collection or view and returns a cursor to the
selected documents.
Definition: db.collection.find(query, projection, options)

Sudhanshu Shekhar Bisoyi Database For Big Data 9 / 62


MongoDB CRUD Operations Query Documents

db.inventory.insertMany([
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm"
}, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in"
}, status: "A" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in"
}, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom:
"cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom:
"cm" }, status: "A" }
]);

Sudhanshu Shekhar Bisoyi Database For Big Data 10 / 62


MongoDB CRUD Operations Query Documents

Comparison Query operators

$lt – Matches values that are less than the value specified in the
query.
$gte – Matches values that are greater than or equal to the value
specified in the query.
$lte – Matches values that are less than or equal to the value
specified in the query.
$ne – Matches all values that are not equal to the value specified in
the query.
$in – Matches any of the values that exist in an array specified in the
query.
$nin – Matches values that do not exist in an array specified in the
query.

Sudhanshu Shekhar Bisoyi Database For Big Data 11 / 62


MongoDB CRUD Operations Query Documents

Logical Query operators

$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.
$or – Joins query clauses with a logical OR returns all documents that
match the conditions of either clause.
$nor – Joins query clauses with a logical NOR returns all documents
that fail to match both clauses..

Sudhanshu Shekhar Bisoyi Database For Big Data 12 / 62


MongoDB CRUD Operations Query Documents

Element Query operators

$exists – Matches documents that have the specified field.


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

Sudhanshu Shekhar Bisoyi Database For Big Data 13 / 62


MongoDB CRUD Operations Query Documents

Evaluation Query operators

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


selects documents with a specified result.
$regex – Selects documents where values match a specified regular
expression.
$where – Matches documents that satisfy a JavaScript expression.

Sudhanshu Shekhar Bisoyi Database For Big Data 14 / 62


MongoDB CRUD Operations Query Documents

Query operator Array

$all – Matches arrays that contain all elements specified in the query.
$elemMatch – Selects documents if an element in the array field
matches all the specified $elemMatch conditions.
$size – Selects documents if the array field is a specified size.

Sudhanshu Shekhar Bisoyi Database For Big Data 15 / 62


MongoDB CRUD Operations Query Documents

Projection operator

$ – Projects the first element in an array that matches the query


condition.
$elemMatch(projection) – Projects the first element in an array that
matches the specified $elemMatch condition.
$slice – Limits the number of elements projected from an array.
Supports skip and limit slices.

Sudhanshu Shekhar Bisoyi Database For Big Data 16 / 62


MongoDB CRUD Operations Query Documents

Select All Documents in a Collection


db.inventory.find( {} )

This operation corresponds to the following SQL statement:


SELECT * FROM inventory

Specify Equality Condition


To specify equality conditions, use < field >:< value > expressions in
the query filter document
The following example selects from the inventory collection all
documents where the status equals ”D”:
db.inventory.find( { status: "D" } )

This operation corresponds to the following SQL statement:


SELECT * FROM inventory WHERE status = "D"

Sudhanshu Shekhar Bisoyi Database For Big Data 17 / 62


MongoDB CRUD Operations Query Documents

Specify Conditions Using Query Operators


A query filter document can use the query operators to specify
conditions in the following form:
{ <field1>: { <operator1>: <value1> }, ... }

The following example retrieves all documents from the inventory


collection where status equals either ”A” or ”D”:
db.inventory.find( { status: { $in: [ "A", "D" ] } } )

The operation corresponds to the following SQL statement:


SELECT * FROM inventory WHERE status in ("A", "D")

Sudhanshu Shekhar Bisoyi Database For Big Data 18 / 62


MongoDB CRUD Operations Query Documents

Specify AND Conditions


A logical AND conjunction connects the clauses of a compound query
so that the query selects the documents in the collection that match
all the conditions.
The following example retrieves all documents in the inventory
collection where the status equals ”A” and qty is less than ($lt) 30:
db.inventory.find( { status: "A", qty: { $lt: 30 } } )

The operation corresponds to the following SQL statement:


SELECT * FROM inventory WHERE status = "A" AND qty < 30

Sudhanshu Shekhar Bisoyi Database For Big Data 19 / 62


MongoDB CRUD Operations Query Documents

Specify OR Conditions
Using the $or operator, you can specify a compound query that joins
each clause with a logical OR conjunction so that the query selects
the documents in the collection that match at least one condition.
The following example retrieves all documents in the collection where
the status equals ”A” or qty is less than ($lt) 30:
db.inventory.find( { $or: [ { status: "A" }, { qty: {
$lt: 30 } } ] } )

The operation corresponds to the following SQL statement:


SELECT * FROM inventory WHERE status = "A" OR qty < 30

Sudhanshu Shekhar Bisoyi Database For Big Data 20 / 62


MongoDB CRUD Operations Query Documents

Specify AND as well as OR Conditions


We can use the compound queries to select documents based on
AND and OR coerator in a single query.
In the following example, the compound query document selects all
documents in the collection where the status equals ”A” and either
qty is less than ($lt) 30 or item starts with the character p:
db.inventory.find( {
status: "A",
$or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
} )

The operation corresponds to the following SQL statement:


SELECT * FROM inventory WHERE status = "A" AND ( qty < 30
OR item LIKE "p%")

Sudhanshu Shekhar Bisoyi Database For Big Data 21 / 62


MongoDB CRUD Operations Query Documents

Query on Embedded/Nested Documents


Now let us discuss the query operations on embedded/nested
documents using the db.collection.find() method in mongoDB.
The examples on this page use the inventory collection. To populate
the inventory collection, run the following: .
db.inventory.insertMany( [
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" },
status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" },
status: "A" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" },
status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm"
}, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm"
}, status: "A" }
]);

Sudhanshu Shekhar Bisoyi Database For Big Data 22 / 62


MongoDB CRUD Operations Query Documents

Match an Embedded or Nested Document


To specify an equality condition on a field that is an embedded or
nested document, use the query filter document < field >:< value >
where < value > is the document to match.
For example, the following query selects all documents where the field
size equals the document h : 14, w : 21, uom : ”cm”:
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )

Equality matches on the whole embedded document require an exact


match of the specified ¡value¿ document, including the field order.
For example, the following query does not match any documents in
the inventory collection:
db.inventory.find( { size: { w: 21, h: 14, uom: "cm" } } )

Sudhanshu Shekhar Bisoyi Database For Big Data 23 / 62


MongoDB CRUD Operations Query Documents

Query on Nested Field


To specify a query condition on fields in an embedded/nested
document, use dot notation (”field.nestedField”).
When querying using dot notation, the field and nested field must be
inside quotation marks.
Specify Equality Match on a Nested Field
The following example selects all documents where the field uom
nested in the size field equals ”in”:
db.inventory.find( { "size.uom": "in" } )

Specify Match using Query Operator


A query filter document can use the query operators to specify
conditions in the following form:
{ <field1>: { <operator1>: <value1> }, ... }

Sudhanshu Shekhar Bisoyi Database For Big Data 24 / 62


MongoDB CRUD Operations Query Documents

The following query uses the less than operator ($lt) on the field h
embedded in the size field:
db.inventory.find( { "size.h": { $lt: 15 } } )

Specify AND Condition


The following query selects all documents where the nested field h is
less than 15, the nested field uom equals ”in”, and the status field
equals ”D”:

db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in",


status: "D" } )

Sudhanshu Shekhar Bisoyi Database For Big Data 25 / 62


MongoDB CRUD Operations Query Documents

Query an Array
This page provides examples of query operations on array fields using
the db.collection.find() method in mongosh. The examples on this
page use the inventory collection. To populate the inventory
collection, run the following:
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [
14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [
14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"],
dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [
22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25
] }
]);

Sudhanshu Shekhar Bisoyi Database For Big Data 26 / 62


MongoDB CRUD Operations Query Documents

Match an Array
To specify equality condition on an array, use the query document
{< field >:< value >} where < value > is the exact array to match,
including the order of the elements.
The following example queries for all documents where the field tags
value is an array with exactly two elements, ”red” and ”blank”, in the
specified order:
db.inventory.find( { tags: ["red", "blank"] } )

If, instead, you wish to find an array that contains both the elements
”red” and ”blank”, without regard to order or other elements in the
array, use the $all operator:
db.inventory.find( { tags: { $all: ["red", "blank"] } } )

Sudhanshu Shekhar Bisoyi Database For Big Data 27 / 62


MongoDB CRUD Operations Query Documents

Query an Array for an Element


To query if the array field contains at least one element with the
specified value, use the filter {< field >:< value >} where < value >
is the element value.
The following example queries for all documents where tags is an
array that contains the string ”red” as one of its elements:
db.inventory.find( { tags: "red" } )

To specify conditions on the elements in the array field, use query


operators in the query filter document:
{ <array field>: { <operator1>: <value1>, ... } }

For example, the following operation queries for all documents where
the array dim cm contains at least one element whose value is greater
than 25.
db.inventory.find( { dim_cm: { $gt: 25 } } )

Sudhanshu Shekhar Bisoyi Database For Big Data 28 / 62


MongoDB CRUD Operations Query Documents

Specify Multiple Conditions for Array Elements

When specifying compound conditions on array elements, you can specify


the query such that either a single array element meets these condition or
any combination of array elements meets the conditions.
Query an Array with Compound Filter Conditions on the Array
Elements
The following example queries for documents where the dim cm array
contains elements that in some combination satisfy the query
conditions; e.g., one element can satisfy the greater than 15 condition
and another element can satisfy the less than 20 condition, or a single
element can satisfy both:
db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )

Sudhanshu Shekhar Bisoyi Database For Big Data 29 / 62


MongoDB CRUD Operations Query Documents

Query for an Array Element that Meets Multiple Criteria


Use $elemMatch operator to specify multiple criteria on the elements
of an array such that at least one array element satisfies all the
specified criteria.
The following example queries for documents where the dim cm array
contains at least one element that is both greater than ($gt) 22 and
less than ($lt) 30:
db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22,
$lt: 30 } } } )

Sudhanshu Shekhar Bisoyi Database For Big Data 30 / 62


MongoDB CRUD Operations Query Documents

Query for an Element by the Array Index Position


Using dot notation, you can specify query conditions for an element
at a particular index or position of the array. The array uses
zero-based indexing.
When querying using dot notation, the field and nested field must be
inside quotation marks.
The following example queries for all documents where the second
element in the array dim cm is greater than 25:
db.inventory.find( { "dim_cm.1": { $gt: 25 } } )

Sudhanshu Shekhar Bisoyi Database For Big Data 31 / 62


MongoDB CRUD Operations Query Documents

Query an Array by Array Length


Use the $size operator to query for arrays by number of elements.
For example, the following selects documents where the array tags
has 3 elements.
db.inventory.find( { "tags": { $size: 3 } } )

Sudhanshu Shekhar Bisoyi Database For Big Data 32 / 62


MongoDB CRUD Operations Query Documents

Project Fields to Return from Query

By default, queries in MongoDB return all fields in matching


documents.
To limit the amount of data that MongoDB sends to applications,
you can include a projection document to specify or restrict fields to
return.
he examples on this page use the inventory collection. To populate
the inventory collection, run the following:

Sudhanshu Shekhar Bisoyi Database For Big Data 33 / 62


MongoDB CRUD Operations Query Documents

db.inventory.insertMany( [
{ item: "journal", status: "A", size: { h: 14, w: 21, uom: "cm"
}, instock: [ { warehouse: "A", qty: 5 } ] },
{ item: "notebook", status: "A", size: { h: 8.5, w: 11, uom:
"in" }, instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", status: "D", size: { h: 8.5, w: 11, uom: "in"
}, instock: [ { warehouse: "A", qty: 60 } ] },
{ item: "planner", status: "D", size: { h: 22.85, w: 30, uom:
"cm" }, instock: [ { warehouse: "A", qty: 40 } ] },
{ item: "postcard", status: "A", size: { h: 10, w: 15.25, uom:
"cm" }, instock: [ { warehouse: "B", qty: 15 }, { warehouse:
"C", qty: 35 } ] }
])

Sudhanshu Shekhar Bisoyi Database For Big Data 34 / 62


MongoDB CRUD Operations Query Documents

Return All Fields in Matching Documents


If you do not specify a projection document, the db.collection.find()
method returns all fields in the matching documents.
The following example returns all fields from all documents in the
inventory collection where the status equals ”A”:
db.inventory.find( { status: "A" } )

Sudhanshu Shekhar Bisoyi Database For Big Data 35 / 62


MongoDB CRUD Operations Query Documents

Return the Specified Fields and the id Field Only


A projection can explicitly include several fields by setting the
< field > to 1 in the projection document. The following operation
returns all documents that match the query. In the result set, only
the item, status and, by default, the id fields return in the matching
documents.
db.inventory.find( { status: "A" }, { item: 1, status: 1 } )

The operation corresponds to the following SQL statement:


SELECT _id, item, status from inventory WHERE status = "A"

Sudhanshu Shekhar Bisoyi Database For Big Data 36 / 62


MongoDB CRUD Operations Query Documents

Suppress id Field
You can remove the id field from the results by setting it to 0 in the
projection, as in the following example:
db.inventory.find( { status: "A" }, { item: 1, status: 1,
_id: 0 } )

The operation corresponds to the following SQL statement:


SELECT item, status from inventory WHERE status = "A"

Sudhanshu Shekhar Bisoyi Database For Big Data 37 / 62


MongoDB CRUD Operations Query Documents

Return All But the Excluded Fields


Instead of listing the fields to return in the matching document, you
can use a projection to exclude specific fields.
The following example which returns all fields except for the status
and the instock fields in the matching documents:

db.inventory.find( { status: "A" }, { status: 0, instock: 0 } )

Sudhanshu Shekhar Bisoyi Database For Big Data 38 / 62


MongoDB CRUD Operations Query Documents

Return Specific Fields in Embedded Documents


You can return specific fields in an embedded document.
Use the dot notation to refer to the embedded field and set to 1 in
the projection document.
The following example returns id, item, status, uom field of size.
The uom field remains embedded in the size document.
db.inventory.find(
{ status: "A" },
{ item: 1, status: 1, "size.uom": 1 }
)

Sudhanshu Shekhar Bisoyi Database For Big Data 39 / 62


MongoDB CRUD Operations Query Documents

Suppress Specific Fields in Embedded Documents


You can suppress specific fields in an embedded document. Use the
dot notation to refer to the embedded field in the projection
document and set to 0.
db.inventory.find(
{ status: "A" },
{ "size.uom": 0 }
)

Sudhanshu Shekhar Bisoyi Database For Big Data 40 / 62


MongoDB CRUD Operations Query Documents

Projection on Embedded Documents in an Array


Use dot notation to project specific fields inside documents embedded
in an array.
db.inventory.find(
{ status: "A" },
{ item: 1, status: 1, "instock.qty": 1 }
)

Sudhanshu Shekhar Bisoyi Database For Big Data 41 / 62


MongoDB CRUD Operations Query Documents

Project Specific Array Elements in the Returned Array


For fields that contain arrays, MongoDB provides the following
projection operators for manipulating arrays: $elemMatch, $slice, and
$
The following example uses the $slice projection operator to return
the last element in the instock array:
db.inventory.find(
{ status: "A" },
{ item: 1, status: 1, instock: { $slice: -1 } }
)

$elemMatch, $slice, and $ are the only way to project specific


elements to include in the returned array.
For instance, you cannot project specific array elements using the
array index; e.g. ”instock.0”: 1 projection will not project the array
with the first element.

Sudhanshu Shekhar Bisoyi Database For Big Data 42 / 62


MongoDB CRUD Operations Query Documents

$slice (projection)
The $slice projection operator specifies the number of elements in an
array to return in the query result.
The $slice has one of the following syntax forms:
db.collection.find(
<query>,
{ <arrayField>: { $slice: <number> } }
)

or
db.collection.find(
<query>,
{ <arrayField>: { $slice:
[ <number to skip>, <number to return> ] } }
)

Sudhanshu Shekhar Bisoyi Database For Big Data 43 / 62


MongoDB CRUD Operations Query Documents

$slice of Embedded Array


The $slice projection of an array in an nested document no longer
returns the other fields in the nested document when the projection is
part of an inclusion projection.
For example, consider a collection inventory with documents that
contain a size field:
db.InvSliceTest.insertOne({ item: "socks", qty: 100,
details: { colors: [ "blue", "red" ],
sizes: [ "S", "M", "L"] } }
)

the following operation projects the id field (by default), the qty field,
and the details field with just the specified slice of the colors array:
db.InvSliceTest.find( { },
{ qty: 1, "details.colors": { $slice: 1 } }
)

Sudhanshu Shekhar Bisoyi Database For Big Data 44 / 62


MongoDB CRUD Operations Query Documents

Examples

Create an example collection posts with the following documents:


db.posts.insertMany([{_id: 1, title: "Bagels are not
croissants.",
comments: [ { comment: "0. true" },
{ comment: "1. croissants aren’t bagels."} ]
},
{_id: 2, title: "Coffee please.",
comments: [ { comment: "0. fooey" },
{ comment: "1. tea please" },
{ comment: "2. iced coffee" },
{ comment: "3. cappuccino" },
{ comment: "4. whatever" } ]
}
])

Sudhanshu Shekhar Bisoyi Database For Big Data 45 / 62


MongoDB CRUD Operations Query Documents

Return an Array with Its First 3 Elements


The following operation uses the $slice projection operator on the
comments array to return the array with its first three elements.
If the array has less than three elements, all elements in the array are
returned.
db.posts.find( {}, { comments: { $slice: 3 } } )

Sudhanshu Shekhar Bisoyi Database For Big Data 46 / 62


MongoDB CRUD Operations Query Documents

Return an Array with Its Last 3 Elements


The following operation uses the $slice projection operator on the
comments array to return the array with its last three elements.
If the array has less than three elements, all elements in the array are
returned.
db.posts.find( {}, { comments: { $slice: -3 } } )

Sudhanshu Shekhar Bisoyi Database For Big Data 47 / 62


MongoDB CRUD Operations Query Documents

Return an Array with 3 Elements After Skipping the First Element


The following operation uses the $slice projection operator on the
comments array to:
Skip the first element such that the second element is the starting
point.
Then, return three elements from the starting point.
If the array has less than three elements after the skip, all remaining
elements are returned.

db.posts.find( {}, { comments: { $slice: [ 1, 3 ] } } )

Sudhanshu Shekhar Bisoyi Database For Big Data 48 / 62


MongoDB CRUD Operations Query Documents

Query for Null or Missing Fields

Let us considr the operations that query for null values using the
db.collection.find() method in mongosh.
The following examples use the inventory collection.
db.inventory.insertMany([
{ _id: 1, item: null },
{ _id: 2 }
])

Sudhanshu Shekhar Bisoyi Database For Big Data 49 / 62


MongoDB CRUD Operations Query Documents

Equality Filter
The { item : null } query matches documents that either contain the
item field whose value is null or that do not contain the item field.
db.inventory.find( { item: null } )

The query returns both documents in the collection.


Type Check
The { item : { $type: 10 } } query matches only documents that
contain the item field whose value is null;
The value of the item field is of BSON Type Null (type number 10) :
db.inventory.find( { item : { $type: 10 } } )

The query returns only the document where the item field has a value
of null.

Sudhanshu Shekhar Bisoyi Database For Big Data 50 / 62


MongoDB CRUD Operations Query Documents

Existence Check
The $exists is used for documents that do not contain a field.
The { item : { $exists: false } } query matches documents that do
not contain the item field.
db.inventory.find( { item : { $exists: false } } )

Sudhanshu Shekhar Bisoyi Database For Big Data 51 / 62


MongoDB CRUD Operations Query Documents

Iterate a Cursor in mongosh

The db.collection.find() method returns a cursor.


To access the documents, you need to iterate the cursor.
However, in mongosh, if the returned cursor is not assigned to a
variable using the var keyword, then the cursor is automatically
iterated up to 20 times to print up to the first 20 documents in the
results.

Sudhanshu Shekhar Bisoyi Database For Big Data 52 / 62


MongoDB CRUD Operations Query Documents

Manually Iterate the Cursor


In mongosh, when you assign the cursor returned from the find()
method to a variable using the var keyword, the cursor does not
automatically iterate.
You can call the cursor variable in the shell to iterate up to 20 times
and print the matching documents, as in the following example:
var myCursor = db.users.find( { type: 2 } )
myCursor

Sudhanshu Shekhar Bisoyi Database For Big Data 53 / 62


MongoDB CRUD Operations Query Documents

You can also use the cursor method next() to access the documents,
as in the following example:
var myCursor = db.users.find( { type: 2 } )
while (myCursor.hasNext()) {
print(tojson(myCursor.next()));
}

Sudhanshu Shekhar Bisoyi Database For Big Data 54 / 62


MongoDB CRUD Operations Query Documents

As an alternative print operation, consider the printjson() helper


method to replace print(tojson()):
var myCursor = db.users.find( { type: 2 } )
while (myCursor.hasNext()) {
printjson(myCursor.next())
}

Sudhanshu Shekhar Bisoyi Database For Big Data 55 / 62


MongoDB CRUD Operations Query Documents

You can use the cursor method forEach() to iterate the cursor and
access the documents, as in the following example:
var myCursor = db.users.find( { type: 2 } )
myCursor.forEach(printjson)

Sudhanshu Shekhar Bisoyi Database For Big Data 56 / 62


MongoDB CRUD Operations Update Documents

Update Documents

We can use the following mongosh methods for updating the documents:
db.collection.updateOne(< filter >, < update >, < options >)
db.collection.updateMany(< filter >, < update >, < options >)
db.collection.replaceOne(< filter >, < update >, < options >)

Sudhanshu Shekhar Bisoyi Database For Big Data 57 / 62


MongoDB CRUD Operations Update Documents

Let us considered the data set for the update operation.


db.inventory.insertMany( [
{ item:"canvas",qty:100,size:{h:28,w:35.5,uom:"cm" },status:"A"},
{item:"journal",qty:25,size:{h:14 w:21,uom:"cm"},status:"A"},
{item:"mat",qty:85,size:{h:27.9,w:35.5,uom:"cm"},status:"A"},
{item:"mousepad",qty:25,size:{h:19,w:22.85,uom:"cm"},status:"P"},
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" },
status: "P" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" },
status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm"
}, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm"
}, status: "A" },
{ item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm"
}, status: "A" },
{ item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom:
"cm" }, status: "A" }
] )

Sudhanshu Shekhar Bisoyi Database For Big Data 58 / 62


MongoDB CRUD Operations Update Documents

Update Documents in a Collection

To update a document, MongoDB provides update operators, such as


$set, to modify field values.
To use the update operators, pass to the update methods an update
document of the form:

{
<update operator>: { <field1>: <value1>, ... },
<update operator>: { <field2>: <value2>, ... },
...
}

Sudhanshu Shekhar Bisoyi Database For Big Data 59 / 62


MongoDB CRUD Operations Update Documents

Update a Single Document


The following example uses the db.collection.updateOne() method on
the inventory collection to update the first document where item
equals ”paper”:
db.inventory.updateOne(
{ item: "paper" },
{
$set: { "size.uom": "cm", status: "P" },
$currentDate: { lastModified: true }
}
)

Sudhanshu Shekhar Bisoyi Database For Big Data 60 / 62


MongoDB CRUD Operations Update Documents

The update operation:


uses the $set operator to update the value of the size.uom field to
”cm” and the value of the status field to ”P”,
uses the $currentDate operator to update the value of the
lastModified field to the current date. If lastModified field does not
exist, $currentDate will create the field

Sudhanshu Shekhar Bisoyi Database For Big Data 61 / 62


MongoDB CRUD Operations Update Documents

db.inventory.updateMany(
{ "qty": { $lt: 50 } },
{
$set: { "size.uom": "in", status: "P" },
$currentDate: { lastModified: true }
}
)

The update operation:


uses the $set operator to update the value of the size.uom field to
”in” and the value of the status field to ”P”
uses the $currentDate operator to update the value of the
lastModified field to the current date. If lastModified field does not
exist, $currentDate will create the field

Sudhanshu Shekhar Bisoyi Database For Big Data 62 / 62


MongoDB CRUD Operations Update Documents

db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 },
{ warehouse: "B", qty: 40 } ] }
)

Sudhanshu Shekhar Bisoyi Database For Big Data 63 / 62

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy