0% found this document useful (0 votes)
180 views

MongoDB CRUD Operations

The document describes MongoDB CRUD (create, read, update, delete) operations. It explains that MongoDB provides methods like insertOne(), insertMany(), find(), updateOne(), updateMany(), deleteOne(), and deleteMany() to perform CRUD operations on documents in a collection. All write operations in MongoDB are atomic at the single document level. Queries can filter documents using the same syntax as read operations.

Uploaded by

Flor Garcia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
180 views

MongoDB CRUD Operations

The document describes MongoDB CRUD (create, read, update, delete) operations. It explains that MongoDB provides methods like insertOne(), insertMany(), find(), updateOne(), updateMany(), deleteOne(), and deleteMany() to perform CRUD operations on documents in a collection. All write operations in MongoDB are atomic at the single document level. Queries can filter documents using the same syntax as read operations.

Uploaded by

Flor Garcia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 70

https://docs.mongodb.

com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf

MongoDB CRUD Operations


CRUD operations create, read, update, and delete documents.

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.insertOne() New in version 3.2


 db.collection.insertMany() New in version 3.2

In MongoDB, insert operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.

For examples, see Insert Documents.

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.

click to enlarge

For examples, see:

 Query Documents
 Query on Embedded/Nested Documents
 Query an Array
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
 Query an Array of Embedded Documents

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.

For examples, see Update Documents.

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.

For examples, see Delete Documents.


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Bulk Write
MongoDB provides the ability to perform write operations in bulk. For details, see Bulk
Write Operations.

Insert Documents

➤ Use the Select your language drop-down menu in the upper-right to set the language of
the examples on this page.

This page provides examples of insert operations in MongoDB.

Note
Creating a Collection

If the collection does not currently exist, insert operations will create the collection.

Insert a Single Document


db.collection.insertOne() inserts a single document into a collection.

The following example inserts a new document into the inventory collection. If the
document does not specify an _id field, MongoDB adds the _id field with an ObjectId
value to the new document. See Insert Behavior.

db.inventory.insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)

You can run the operation in the web shell below:

insertOne() returns a document that includes the newly inserted document's _id field
value. For an example of a return document, see db.collection.insertOne() reference.

To retrieve the document that you just inserted, query the collection:
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
db.inventory.find( { item: "canvas" } )

Insert Multiple Documents

➤ Use the Select your language drop-down menu in the upper-right to set the language of
the examples on this page.

New in version 3.2.

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. If the
documents do not specify an _id field, MongoDB adds the _id field with an ObjectId
value to each document. See Insert Behavior.

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

You can run the operation in the web shell below:

insertMany() returns a document that includes the newly inserted documents _id field
values. See the reference for an example.

To retrieve the inserted documents, query the collection:

db.inventory.find( {} )

Insert Behavior
Collection Creation

If the collection does not currently exist, insert operations will create the collection.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
_id Field

In MongoDB, each document stored in a collection requires a unique _id field that acts as a
primary key. If an inserted document omits the _id field, the MongoDB driver
automatically generates an ObjectId for the _id field.

This also applies to documents inserted through update operations with upsert: true.

Atomicity

All write operations in MongoDB are atomic on the level of a single document. For more
information on MongoDB and atomicity, see Atomicity and Transactions

Write Acknowledgement

With write concerns, you can specify the level of acknowledgement requested from
MongoDB for write operations. For details, see Write Concern.

Tip
See also:

 db.collection.insertOne()
 db.collection.insertMany()
 Additional Methods for Inserts

Insert Methods
MongoDB provides the following methods for inserting documents into a collection:

db.collection.insertOne()
Inserts a single document into a
collection.
db.collection.insertMany()Inserts multiple documents into a collection.

Additional Methods for Inserts


The following methods can also add new documents to a collection:

 db.collection.updateOne() when used with the upsert: true option.


 db.collection.updateMany() when used with the upsert: true option.
 db.collection.findAndModify() when used with the upsert: true option.
 db.collection.findOneAndUpdate() when used with the upsert: true option.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
 db.collection.findOneAndReplace() when used with the upsert: true option.
 db.collection.bulkWrite().

See the individual reference pages for the methods for more information and examples.

Query Documents

➤ Use the Select your language drop-down menu in the upper-right to set the language of
the following examples.

This page provides examples of query operations using MongoDB Compass. The examples
on this page use the inventory collection. Populate the inventory collection with the
following documents:

[
{ 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" }
]

For instructions on inserting documents in MongoDB Compass, see Insert Documents.

Select All Documents in a Collection


To select all documents in the collection, pass an empty document as the query filter
parameter to the query bar. The query filter parameter determines the select criteria:
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf

This operation corresponds to the following SQL statement:

SELECT * FROM inventory

For more information on the MongoDB Compass query bar, see Query Bar.

Specify Equality Condition


To specify equality conditions, use <field>:<value> expressions in the query filter
document:
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
{ <field1>: <value1>, ... }

The following example selects from the inventory collection all documents where the
status equals "D":

Copy the following filter into the Compass query bar and click Find:

{ status: "D" }

This operation corresponds to the following SQL statement:

SELECT * FROM inventory WHERE status = "D"


Note

The MongoDB Compass query bar autocompletes the current query based on the keys in
your collection's documents, including keys in embedded sub-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> }, ... }


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
The following example retrieves all documents from the inventory collection where
status equals either "A" or "D":

Copy the following filter into the Compass query bar and click Find:

{ status: { $in: [ "A", "D" ] } }

Note

Although you can express this query using the $or operator, use the $in operator rather
than the $or operator when performing equality checks on the same field.

The operation corresponds to the following SQL statement:

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


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Refer to the Query and Projection Operators document for the complete list of MongoDB
query operators.

Specify AND Conditions


A compound query can specify conditions for more than one field in the collection's
documents. Implicitly, 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:

Copy the following filter into the Compass query bar and click Find:

{ status: "A", qty: { $lt: 30 } }

The operation corresponds to the following SQL statement:

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

See comparison operators for other MongoDB comparison operators.

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:
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Copy the following filter into the Compass query bar and click Find:

{ $or: [ { status: "A" }, { qty: { $lt: 30 } } ] }

The operation corresponds to the following SQL statement:

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


Note

Queries which use comparison operators are subject to Type Bracketing.

Specify AND as well as OR Conditions

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:

Copy the following filter into the Compass query bar and click Find:

{ status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ] }


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf

The operation corresponds to the following SQL statement:

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

MongoDB supports regular expressions $regex queries to perform string pattern matches.

Additional Query Tutorials


For additional query examples, see:

 Query on Embedded/Nested Documents


 Query an Array
 Query an Array of Embedded Documents
 Project Fields to Return from Query
 Query for Null or Missing Fields

Behavior
Cursor

The MongoDB Compass Find operation opens a cursor to the matching documents of the
collection based on the find query.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
For more information on sampling in MongoDB Compass, see the Compass FAQ.

Read Isolation

New in version 3.2.

For reads to replica sets and replica set shards, read concern allows clients to choose a level
of isolation for their reads. For more information, see Read Concern.

Query on Embedded/Nested Documents

➤ Use the Select your language drop-down menu in the upper-right to set the language of
the following examples.

This page provides examples of query operations on embedded/nested documents using


MongoDB Compass. The examples on this page use the inventory collection. Populate
the inventory collection with the following documents:

[
{ 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" }
]

For instructions on inserting documents in MongoDB Compass, see Insert Documents.

Match an Embedded/Nested Document


To specify an equality condition on a field that is an embedded/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" }:
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Copy the following filter into the Compass query bar and click 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:

Query on Nested Field


To specify a query condition on fields in an embedded/nested document, use dot notation
("field.nestedField").

Note

When querying using dot notation, the field and nested field must be inside quotation
marks.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Specify Equality Match on a Nested Field

The following example selects all documents where the field uom nested in the size field
equals "in":

Copy the following filter into the Compass query bar and click 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> }, ... }

The following query uses the less than operator ($lt) on the field h embedded in the size
field:

Copy the following filter into the Compass query bar and click Find:
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
{ "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":

Copy the following filter into the Compass query bar and click Find:

{ "size.h": { $lt: 15 }, "size.uom": "in", status: "D" }


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf

Additional Query Tutorials


For additional query examples, see:

 Query Documents
 Query an Array
 Query an Array of Embedded Documents

Query an Array

➤ Use the Select your language drop-down menu in the upper-right to set the language of
the following examples.

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 ] },
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);

You can run the operation in the web shell below:

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

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


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
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 } } )


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


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.

Note

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


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.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
db.inventory.find( { "tags": { $size: 3 } } )

Additional Query Tutorials


For additional query examples, see:

 Query Documents
 Query on Embedded/Nested Documents
 Query an Array of Embedded Documents

Query an Array of Embedded Documents

➤ Use the Select your language drop-down menu in the upper-right to set the language of
the following examples.

This page provides examples of query operations on an array of nested documents 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", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);

You can run the operation in the web shell below:

Query for a Document Nested in an Array


The following example selects all documents where an element in the instock array
matches the specified document:

db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Equality matches on the whole embedded/nested document require an exact match of the
specified document, including the field order. For example, the following query does not
match any documents in the inventory collection:

db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )

Specify a Query Condition on a Field in an Array of


Documents
Specify a Query Condition on a Field Embedded in an Array of Documents

If you do not know the index position of the document nested in the array, concatenate the
name of the array field, with a dot (.) and the name of the field in the nested document.

The following example selects all documents where the instock array has at least one
embedded document that contains the field qty whose value is less than or equal to 20:

db.inventory.find( { 'instock.qty': { $lte: 20 } } )


Use the Array Index to Query for a Field in the Embedded Document

Using dot notation, you can specify query conditions for field in a document at a particular
index or position of the array. The array uses zero-based indexing.

Note

When querying using dot notation, the field and index must be inside quotation marks.

The following example selects all documents where the instock array has as its first
element a document that contains the field qty whose value is less than or equal to 20:

db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )

Specify Multiple Conditions for Array of Documents


When specifying conditions on more than one field nested in an array of documents, you
can specify the query such that either a single document meets these condition or any
combination of documents (including a single document) in the array meets the conditions.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
A Single Nested Document Meets Multiple Query Conditions on Nested Fields

Use $elemMatch operator to specify multiple criteria on an array of embedded documents


such that at least one embedded document satisfies all the specified criteria.

The following example queries for documents where the instock array has at least one
embedded document that contains both the field qty equal to 5 and the field warehouse
equal to A:

db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )

The following example queries for documents where the instock array has at least one
embedded document that contains the field qty that is greater than 10 and less than or equal
to 20:

db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )


Combination of Elements Satisfies the Criteria

If the compound query conditions on an array field do not use the $elemMatch operator, the
query selects those documents whose array contains any combination of elements that
satisfies the conditions.

For example, the following query matches documents where any document nested in the
instock array has the qty field greater than 10 and any document (but not necessarily the
same embedded document) in the array has the qty field less than or equal to 20:

db.inventory.find( { "instock.qty": { $gt: 10, $lte: 20 } } )

The following example queries for documents where the instock array has at least one
embedded document that contains the field qty equal to 5 and at least one embedded
document (but not necessarily the same embedded document) that contains the field
warehouse equal to A:

db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )

Additional Query Tutorials


For additional query examples, see:

 Query an Array
 Query Documents
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
 Query on Embedded/Nested Documents

Project Fields to Return from Query

➤ Use the Select your language drop-down menu in the upper-right to set the language of
the following examples.

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.

This page provides examples of query operations with projection 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", 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 } ] }
]);

You can run the operation in the web shell below:

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.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
The following example returns all fields from all documents in the inventory collection
where the status equals "A":

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

The operation corresponds to the following SQL statement:

SELECT * from inventory WHERE status = "A"

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"

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"


Note

With the exception of the _id field, you cannot combine inclusion and exclusion statements
in projection documents.

Return All But the Excluded Fields


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
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 } )


Note

With the exception of the _id field, you cannot combine inclusion and exclusion statements
in projection 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:

 The _id field (returned by default),


 The item field,
 The status field,
 The uom field in the size document.

The uom field remains embedded in the size document.

db.inventory.find(
{ status: "A" },
{ item: 1, status: 1, "size.uom": 1 }
)

Starting in MongoDB 4.4, you can also specify embedded fields using the nested form, e.g.
{ item: 1, status: 1, size: { uom: 1 } }.

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.

The following example specifies a projection to exclude the uom field inside the size
document. All other fields are returned in the matching documents:

db.inventory.find(
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
{ status: "A" },
{ "size.uom": 0 }
)

Starting in MongoDB 4.4, you can also specify embedded fields using the nested form, e.g.
{ size: { uom: 0 } }.

Projection on Embedded Documents in an Array


Use dot notation to project specific fields inside documents embedded in an array.

The following example specifies a projection to return:

 The _id field (returned by default),


 The item field,
 The status field,
 The qty field in the documents embedded in the instock array.

db.inventory.find( { status: "A" }, { item: 1, status: 1, "instock.qty": 1 } )

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.

Additional Considerations
Starting in MongoDB 4.4, MongoDB enforces additional restrictions with regards to
projections. See Projection Restrictions for details.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Tip
See also:

 Projection
 Query Documents

← 

Query for Null or Missing Fields

➤ Use the Select your language drop-down menu in the upper-right to set the language of
the following examples.

Different query operators in MongoDB treat null values differently.

This page provides examples of operations that query for null values using the
MongoCollection.Find() method in the MongoDB C# Driver. The examples on this page
use the inventory collection. To populate the inventory collection, run the following:

Important

Use BsonNull.Value with the MongoDB C# driver to query for null or missing fields in
MongoDB.

var documents = new[]


{
new BsonDocument { { "_id", 1 }, { "item", BsonNull.Value } },
new BsonDocument { { "_id", 2 } }
};
collection.InsertMany(documents);

Equality Filter
The Eq("item", BsonNull.Value) query using the FilterDefinitionBuilder.Eq() method
matches documents that either contain the item field whose value is null or that do not
contain the item field.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
var filter = Builders<BsonDocument>.Filter.Eq("item", BsonNull.Value);
var result = collection.Find(filter).ToList();

The query returns both documents in the collection.

Type Check
The Type("item", BsonType.Null) query using the FilterDefinitionBuilder.Type()
method matches only documents that contain the item field whose value is null; i.e. the
value of the item field is of BSON Type Null (type number 10) :

var filter = Builders<BsonDocument>.Filter.Type("item", BsonType.Null);


var result = collection.Find(filter).ToList();

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

Existence Check
The following example queries for documents that do not contain a field. [1]

The Exists("item", false) query using the FilterDefinitionBuilder.Exists() method


matches documents that do not contain the item field:

var filter = Builders<BsonDocument>.Filter.Exists("item", false);


var result = collection.Find(filter).ToList();

The query only returns the document that does not contain the item field.

Tip
See also:

Reference documentation for the $type and $exists operators.

Starting in MongoDB 4.2, users can no longer use the query filter $type: 0 as a
[1] synonym for $exists:false. To query for null or missing fields, see Query for Null or
Missing Fields.

Iterate a Cursor in mongosh


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
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 [1]
to print up to the first 20 documents in the results.

The following examples describe ways to manually iterate the cursor to access the
documents or to use the iterator index.

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 [1] and print the
matching documents, as in the following example:

var myCursor = db.users.find( { type: 2 } );


myCursor

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

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

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);
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
See JavaScript cursor methods and your driver documentation for more information on
cursor methods.

(1, 2) You can set the DBQuery.shellBatchSize attribute to change the number of
[1]
documents from the default value of 20.

Iterator Index
In mongosh, you can use the toArray() method to iterate the cursor and return the
documents in an array, as in the following:

var myCursor = db.inventory.find( { type: 2 } );


var documentArray = myCursor.toArray();
var myDocument = documentArray[3];

The toArray() method loads into RAM all documents returned by the cursor; the
toArray() method exhausts the cursor.

Additionally, some Drivers provide access to the documents by using an index on the
cursor (i.e. cursor[index]). This is a shortcut for first calling the toArray() method and
then using an index on the resulting array.

Consider the following example:

var myCursor = db.users.find( { type: 2 } );


var myDocument = myCursor[1];

The myCursor[1] is equivalent to the following example:

myCursor.toArray() [1];

Cursor Behaviors
Cursors Opened Within a Session

Starting in MongoDB 5.0 (and 4.4.8), cursors created within a client session close when the
corresponding server session ends with the killSessions command, if the session times
out, or if the client has exhausted the cursor.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
By default, server sessions have an expiration timeout of 30 minutes. To change the value,
set the localLogicalSessionTimeoutMinutes parameter when starting up mongod.

Cursors Opened Outside of a Session

Cursors that aren't opened under a session automatically close after 10 minutes of
inactivity, or if client has exhausted the cursor. To override this behavior in mongosh, you
can use the cursor.noCursorTimeout() method:

var myCursor = db.users.find().noCursorTimeout();

After setting the noCursorTimeout option, you must either close the cursor manually with
cursor.close() or by exhausting the cursor's results.

See your driver documentation for information on setting the noCursorTimeout option.

Cursor Isolation

As a cursor returns documents, other operations may interleave with the query.

Cursor Batches

The MongoDB server returns the query results in batches. The amount of data in the batch
will not exceed the maximum BSON document size. To override the default size of the
batch, see batchSize() and limit().

New in version 3.4: Operations of type find(), aggregate(), listIndexes, and


listCollections return a maximum of 16 megabytes per batch. batchSize() can enforce
a smaller limit, but not a larger one.

find() and aggregate() operations have an initial batch size of 101 documents by
default. Subsequent getMore operations issued against the resulting cursor have no default
batch size, so they are limited only by the 16 megabyte message size.

For queries that include a sort operation without an index, the server must load all the
documents in memory to perform the sort before returning any results.

As you iterate through the cursor and reach the end of the returned batch, if there are more
results, cursor.next() will perform a getMore operation to retrieve the next batch. To
see how many documents remain in the batch as you iterate the cursor, you can use the
objsLeftInBatch() method, as in the following example:
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
var myCursor = db.inventory.find();
var myFirstDocument = myCursor.hasNext() ? myCursor.next() : null;
myCursor.objsLeftInBatch();

Cursor Information
The db.serverStatus() method returns a document that includes a metrics field. The
metrics field contains a metrics.cursor field with the following information:

 number of timed out cursors since the last server restart


 number of open cursors with the option DBQuery.Option.noTimeout set to
prevent timeout after a period of inactivity
 number of "pinned" open cursors
 total number of open cursors

Consider the following example which calls the db.serverStatus() method and accesses
the metrics field from the results and then the cursor field from the metrics field:

db.serverStatus().metrics.cursor

The result is the following document:

{
"timedOut" : <number>
"open" : {
"noTimeout" : <number>,
"pinned" : <number>,
"total" : <number>
}
}
Tip
See also:

db.serverStatus()

Update Documents
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
➤ Use the Select your language drop-down menu in the upper-right to set the language of
the following examples.

This page uses the following MongoDB C# Driver methods:

 IMongoCollection.UpdateOne()
 IMongoCollection.UpdateMany()
 IMongoCollection.ReplaceOne()

The examples on this page use the

inventory

collection. To create and/or populate the

inventory

collection, run the following:

var documents = new[]


{
new BsonDocument
{
{ "item", "canvas" },
{ "qty", 100 },
{ "size", new BsonDocument { { "h", 28 }, { "w", 35.5 }, { "uom", "cm" } } },
{ "status", "A" }
},
new BsonDocument
{
{ "item", "journal" },
{ "qty", 25 },
{ "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } } },
{ "status", "A" }
},
new BsonDocument
{
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
{ "item", "mat" },
{ "qty", 85 },
{ "size", new BsonDocument { { "h", 27.9 }, { "w", 35.5 }, { "uom", "cm" } } },
{ "status", "A" }
},
new BsonDocument
{
{ "item", "mousepad" },
{ "qty", 25 },
{ "size", new BsonDocument { { "h", 19 }, { "w", 22.85 }, { "uom", "cm" } } },
{ "status", "P" }
},
new BsonDocument
{
{ "item", "notebook" },
{ "qty", 50 },
{ "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
{ "status", "P" } },
new BsonDocument
{
{ "item", "paper" },
{ "qty", 100 },
{ "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
{ "status", "D" }
},
new BsonDocument
{
{ "item", "planner" },
{ "qty", 75 },
{ "size", new BsonDocument { { "h", 22.85 }, { "w", 30 }, { "uom", "cm" } } },
{ "status", "D" }
},
new BsonDocument
{
{ "item", "postcard" },
{ "qty", 45 },
{ "size", new BsonDocument { { "h", 10 }, { "w", 15.25 }, { "uom", "cm" } } },
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
{ "status", "A" }
},
new BsonDocument
{
{ "item", "sketchbook" },
{ "qty", 80 },
{ "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } } },
{ "status", "A" }
},
new BsonDocument
{
{ "item", "sketch pad" },
{ "qty", 95 },
{ "size", new BsonDocument { { "h", 22.85 }, { "w", 30.5 }, { "uom", "cm" } } }, { "status",
"A" } },
};
collection.InsertMany(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>, ... },
...
}

Some update operators, such as $set, will create the field if the field does not exist. See the
individual update operator reference for details.

Note

Starting in MongoDB 4.2, MongoDB can accept an aggregation pipeline to specify the
modifications to make instead of an update document. See the method reference page for
details.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Update a Single Document

The following example uses the IMongoCollection.UpdateOne() method on the inventory


collection to update the first document where item equals "paper":

var filter = Builders<BsonDocument>.Filter.Eq("item", "paper");


var update = Builders<BsonDocument>.Update.Set("size.uom", "cm").Set("status",
"P").CurrentDate("lastModified");
var result = collection.UpdateOne(filter, update);

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. See $currentDate for details.

var filter = Builders<BsonDocument>.Filter.Lt("qty", 50);


var update = Builders<BsonDocument>.Update.Set("size.uom", "in").Set("status",
"P").CurrentDate("lastModified");
var result = collection.UpdateMany(filter, update);

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. See $currentDate for details.

var filter = Builders<BsonDocument>.Filter.Eq("item", "paper");


var replacement = new BsonDocument
{
{ "item", "paper" },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "A" }, { "qty", 60 } },
new BsonDocument { { "warehouse", "B" }, { "qty", 40 } } }
}
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
};
var result = collection.ReplaceOne(filter, replacement);

Behavior
Atomicity

All write operations in MongoDB are atomic on the level of a single document. For more
information on MongoDB and atomicity, see Atomicity and Transactions.

_id Field

Once set, you cannot update the value of the _id field nor can you replace an existing
document with a replacement document that has a different _id field value.

Field Order

For write operations, MongoDB preserves the order of the document fields except for the
following cases:

 The _id field is always the first field in the document.


 Updates that include renaming of field names may result in the reordering of fields
in the document.

Write Acknowledgement

With write concerns, you can specify the level of acknowledgement requested from
MongoDB for write operations. For details, see Write Concern.

Tip
See also:

 IMongoCollection.UpdateOne()
 IMongoCollection.UpdateMany()
 IMongoCollection.ReplaceOne()
 Additional Methods

Updates with Aggregation Pipeline


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Starting in MongoDB 4.2, you can use the aggregation pipeline for update operations. With
the update operations, the aggregation pipeline can consist of the following stages:

 $addFields
 $set
 $project
 $unset
 $replaceRoot
 $replaceWith

Using the aggregation pipeline allows for a more expressive update statement, such as
expressing conditional updates based on current field values or updating one field using the
value of another field(s).

Example 1
Tip

You can try out the example in the provided shell. Click inside the shell to connect. Once
connected, you can run the examples in the shell.

Create an example students collection (if the collection does not currently exist, insert
operations will create the collection):

db.students.insertMany( [
{ _id: 1, test1: 95, test2: 92, test3: 90, modified: new Date("01/05/2020") },
{ _id: 2, test1: 98, test2: 100, test3: 102, modified: new Date("01/05/2020") },
{ _id: 3, test1: 95, test2: 110, modified: new Date("01/04/2020") }
])

To verify, query the collection:

db.students.find()

The following db.collection.updateOne() operation uses an aggregation pipeline to


update the document with _id: 3:

db.students.updateOne( { _id: 3 }, [ { $set: { "test3": 98, modified: "$$NOW"} } ] )

Specifically, the pipeline consists of a $set stage which adds the test3 field (and sets its
value to 98) to the document and sets the modified field to the current datetime. The
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
operation uses the aggregation variable NOW for the current datetime. To access the variable,
prefix with $$ and enclose in quotes.

To verify the update, you can query the collection:

db.students.find().pretty()

Example 2
Tip

You can try out the example in the provided shell. Click inside the shell to connect. Once
connected, you can run the examples in the shell.

Create an example students2 collection (if the collection does not currently exist, insert
operations will create the collection):

db.students2.insertMany( [
{ "_id" : 1, quiz1: 8, test2: 100, quiz2: 9, modified: new Date("01/05/2020") },
{ "_id" : 2, quiz2: 5, test1: 80, test2: 89, modified: new Date("01/05/2020") },
])

To verify, query the collection:

db.students2.find()

The following db.collection.updateMany() operation uses an aggregation pipeline to


standardize the fields for the documents (i.e. documents in the collection should have the
same fields) and update the modified field:

db.students2.updateMany( {},
[
{ $replaceRoot: { newRoot:
{ $mergeObjects: [ { quiz1: 0, quiz2: 0, test1: 0, test2: 0 }, "$$ROOT" ] }
} },
{ $set: { modified: "$$NOW"} }
]
)

Specifically, the pipeline consists of:


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
 a $replaceRoot stage with a $mergeObjects expression to set default values for
the quiz1, quiz2, test1 and test2 fields. The aggregation variable ROOT refers to
the current document being modified. To access the variable, prefix with $$ and
enclose in quotes. The current document fields will override the default values.
 a $set stage to update the modified field to the current datetime. The operation
uses the aggregation variable NOW for the current datetime. To access the variable,
prefix with $$ and enclose in quotes.

To verify the update, you can query the collection:

db.students2.find()

Example 3
Tip

You can try out the example in the provided shell. Click inside the shell to connect. Once
connected, you can run the examples in the shell.

Create an example students3 collection (if the collection does not currently exist, insert
operations will create the collection):

db.students3.insertMany( [
{ "_id" : 1, "tests" : [ 95, 92, 90 ], "modified" : ISODate("2019-01-01T00:00:00Z") },
{ "_id" : 2, "tests" : [ 94, 88, 90 ], "modified" : ISODate("2019-01-01T00:00:00Z") },
{ "_id" : 3, "tests" : [ 70, 75, 82 ], "modified" : ISODate("2019-01-01T00:00:00Z") }
] );

To verify, query the collection:

db.students3.find()

The following db.collection.updateMany() operation uses an aggregation pipeline to


update the documents with the calculated grade average and letter grade.

db.students3.updateMany(
{ },
[
{ $set: { average : { $trunc: [ { $avg: "$tests" }, 0 ] }, modified: "$$NOW" } },
{ $set: { grade: { $switch: {
branches: [
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
{ case: { $gte: [ "$average", 90 ] }, then: "A" },
{ case: { $gte: [ "$average", 80 ] }, then: "B" },
{ case: { $gte: [ "$average", 70 ] }, then: "C" },
{ case: { $gte: [ "$average", 60 ] }, then: "D" }
],
default: "F"
}}}}
]
)

Specifically, the pipeline consists of:

 a $set stage to calculate the truncated average value of the tests array elements
and to update the modified field to the current datetime. To calculate the truncated
average, the stage uses the $avg and $trunc expressions. The operation uses the
aggregation variable NOW for the current datetime. To access the variable, prefix
with $$ and enclose in quotes.
 a $set stage to add the grade field based on the average using the $switch
expression.

To verify the update, you can query the collection:

db.students3.find()

Example 4
Tip

You can try out the example in the provided shell. Click inside the shell to connect. Once
connected, you can run the examples in the shell.

Create an example students4 collection (if the collection does not currently exist, insert
operations will create the collection):

db.students4.insertMany( [
{ "_id" : 1, "quizzes" : [ 4, 6, 7 ] },
{ "_id" : 2, "quizzes" : [ 5 ] },
{ "_id" : 3, "quizzes" : [ 10, 10, 10 ] }
])
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
To verify, query the collection:

db.students4.find()

The following db.collection.updateOne() operation uses an aggregation pipeline to add


quiz scores to the document with _id: 2:

db.students4.updateOne( { _id: 2 },
[ { $set: { quizzes: { $concatArrays: [ "$quizzes", [ 8, 6 ] ] } } } ]
)

To verify the update, query the collection:

db.students4.find()

Example 5
Tip

You can try out the example in the provided shell. Click inside the shell to connect. Once
connected, you can run the examples in the shell.

Create an example temperatures collection that contains temperatures in Celsius (if the
collection does not currently exist, insert operations will create the collection):

db.temperatures.insertMany( [
{ "_id" : 1, "date" : ISODate("2019-06-23"), "tempsC" : [ 4, 12, 17 ] },
{ "_id" : 2, "date" : ISODate("2019-07-07"), "tempsC" : [ 14, 24, 11 ] },
{ "_id" : 3, "date" : ISODate("2019-10-30"), "tempsC" : [ 18, 6, 8 ] }
])

To verify, query the collection:

db.temperatures.find()

The following db.collection.updateMany() operation uses an aggregation pipeline to


update the documents with the corresponding temperatures in Fahrenheit:

db.temperatures.updateMany( { },
[
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
{ $addFields: { "tempsF": {
$map: {
input: "$tempsC",
as: "celsius",
in: { $add: [ { $multiply: ["$$celsius", 9/5 ] }, 32 ] }
}
}}}
]
)

Specifically, the pipeline consists of an $addFields stage to add a new array field tempsF
that contains the temperatures in Fahrenheit. To convert each celsius temperature in the
tempsC array to Fahrenheit, the stage uses the $map expression with $add and $multiply
expressions.

To verify the update, you can query the collection:

db.temperatures.find()

Additional Examples
See also the various update method pages for additional examples:

 db.collection.updateOne
 db.collection.updateMany
 db.collection.findOneAndUpdate()
 db.collection.findAndModify()
 Bulk.find.update()
 Bulk.find.updateOne()
 Bulk.find.upsert()

Update Methods
MongoDB provides the following methods for updating documents in a collection:

Updates at most a single document that match a specified


db.collection.updateOne() filter even though multiple documents may match the
specified filter.
db.collection.updateMany()Update all documents that match a specified filter.
db.collection.replaceOne()Replaces at most a single document that match a specified
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
filter even though multiple documents may match the
specified filter.

Additional Methods
The following methods can also update documents from a collection:

 db.collection.findOneAndReplace().
 db.collection.findOneAndUpdate().
 db.collection.findAndModify().
 db.collection.bulkWrite().

See the individual reference pages for the methods for more information and examples.

Delete Documents

➤ Use the Select your language drop-down menu in the upper-right to set the language of
the following examples.

This page uses the following MongoDB C# Driver methods:

 IMongoCollection.DeleteMany()
 IMongoCollection.DeleteOne()

The examples on this page use the inventory collection. To populate the inventory
collection, run the following:

var documents = new[]


{
new BsonDocument
{
{ "item", "journal" },
{ "qty", 25 },
{ "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } } },
{ "status", "A" }
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
},
new BsonDocument
{
{ "item", "notebook" },
{ "qty", 50 },
{ "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
{ "status", "P" }
},
new BsonDocument
{
{ "item", "paper" },
{ "qty", 100 },
{ "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
{ "status", "D" }
},
new BsonDocument
{
{ "item", "planner" },
{ "qty", 75 },
{ "size", new BsonDocument { { "h", 22.85 }, { "w", 30 }, { "uom", "cm" } } },
{ "status", "D" }
},
new BsonDocument
{
{ "item", "postcard" },
{ "qty", 45 },
{ "size", new BsonDocument { { "h", 10 }, { "w", 15.25 }, { "uom", "cm" } } },
{ "status", "A" }
}
};
collection.InsertMany(documents);

Delete All Documents


To delete all documents from a collection, pass an empty filter
Builders<BsonDocument>.Filter.Empty to the IMongoCollection.DeleteMany()
method.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
The following example deletes all documents from the inventory collection:

var filter = Builders<BsonDocument>.Filter.Empty;


var result = collection.DeleteMany(filter);

Upon successful execution, the IMongoCollection.DeleteMany() method returns an


instance of DeleteResult whose DeletedCount property contains the number of documents
that matched the filter.

Delete All Documents that Match a Condition


You can specify criteria, or filters, that identify the documents to delete. The filters use the
same syntax as read operations.

To specify equality conditions, construct a filter using the Eq method:

Builders<BsonDocument>.Filter.Eq(<field>, <value>);

In addition to the equality filter, MongoDB provides various query operators to specify
filter conditions. Use the FilterDefinitionBuilder methods to create a filter document. For
example:

var builder = Builders<BsonDocument>.Filter;


builder.And(builder.Eq(<field1>, <value1>), builder.Lt(<field2>, <value2>));

To delete all documents that match a deletion criteria, pass a filter parameter to the
IMongoCollection.DeleteMany() method.

The following example removes all documents from the inventory collection where the
status field equals "A":

var filter = Builders<BsonDocument>.Filter.Eq("status", "A");


var result = collection.DeleteMany(filter);

Upon successful execution, the IMongoCollection.DeleteMany() method returns an


instance of DeleteResult whose DeletedCount property contains the number of documents
that matched the filter.

Delete Only One Document that Matches a Condition


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
To delete at most a single document that matches a specified filter (even though multiple
documents may match the specified filter) use the IMongoCollection.DeleteOne() method.

The following example deletes the first document where status is "D":

var filter = Builders<BsonDocument>.Filter.Eq("status", "D");


var result = collection.DeleteOne(filter);

Delete Behavior
Indexes

Delete operations do not drop indexes, even if deleting all documents from a collection.

Atomicity

All write operations in MongoDB are atomic on the level of a single document. For more
information on MongoDB and atomicity, see Atomicity and Transactions.

Write Acknowledgement

With write concerns, you can specify the level of acknowledgement requested from
MongoDB for write operations. For details, see Write Concern.

Tip
See also:

 IMongoCollection.DeleteMany()
 IMongoCollection.DeleteOne()
 Additional Methods

Delete Methods
MongoDB provides the following methods to delete documents of a collection:

Delete at most a single document that match a specified


filter even though multiple documents may match the
db.collection.deleteOne() specified filter.

New in version 3.2.


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Delete all documents that match a specified filter.
db.collection.deleteMany()
New in version 3.2.
db.collection.remove()
Delete a single document or all documents that match a
specified filter.

Additional Methods
The following methods can also delete documents from a collection:

 db.collection.findOneAndDelete().

findOneAndDelete() provides a sort option. The option allows for the deletion of
the first document sorted by the specified order.

 db.collection.findAndModify().

db.collection.findAndModify() provides a sort option. The option allows for


the deletion of the first document sorted by the specified order.

 db.collection.bulkWrite().

See the individual reference pages for the methods for more information and examples.

Bulk Write Operations


Overview
MongoDB provides clients the ability to perform write operations in bulk. Bulk write
operations affect a single collection. MongoDB allows applications to determine the
acceptable level of acknowledgement required for bulk write operations.

New in version 3.2.

The db.collection.bulkWrite() method provides the ability to perform bulk insert,


update, and remove operations. MongoDB also supports bulk insert through the
db.collection.insertMany().

Ordered vs Unordered Operations


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Bulk write operations can be either ordered or unordered.

With an ordered list of operations, MongoDB executes the operations serially. If an error
occurs during the processing of one of the write operations, MongoDB will return without
processing any remaining write operations in the list. See ordered Bulk Write

With an unordered list of operations, MongoDB can execute the operations in parallel, but
this behavior is not guaranteed. If an error occurs during the processing of one of the write
operations, MongoDB will continue to process remaining write operations in the list. See
Unordered Bulk Write.

Executing an ordered list of operations on a sharded collection will generally be slower


than executing an unordered list since with an ordered list, each operation must wait for the
previous operation to finish.

By default, bulkWrite() performs ordered operations. To specify unordered write


operations, set ordered : false in the options document.

See Execution of Operations

bulkWrite() Methods
bulkWrite() supports the following write operations:

 insertOne
 updateOne
 updateMany
 replaceOne
 deleteOne
 deleteMany

Each write operation is passed to bulkWrite() as a document in an array.

For example, the following performs multiple write operations:

The characters collection contains the following documents:

{ "_id" : 1, "char" : "Brisbane", "class" : "monk", "lvl" : 4 },


{ "_id" : 2, "char" : "Eldon", "class" : "alchemist", "lvl" : 3 },
{ "_id" : 3, "char" : "Meldane", "class" : "ranger", "lvl" : 3 }
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
The following bulkWrite() performs multiple operations on the collection:

try {
db.characters.bulkWrite(
[
{ insertOne :
{
"document" :
{
"_id" : 4, "char" : "Dithras", "class" : "barbarian", "lvl" : 4
}
}
},
{ insertOne :
{
"document" :
{
"_id" : 5, "char" : "Taeln", "class" : "fighter", "lvl" : 3
}
}
},
{ updateOne :
{
"filter" : { "char" : "Eldon" },
"update" : { $set : { "status" : "Critical Injury" } }
}
},
{ deleteOne :
{ "filter" : { "char" : "Brisbane" } }
},
{ replaceOne :
{
"filter" : { "char" : "Meldane" },
"replacement" : { "char" : "Tanys", "class" : "oracle", "lvl" : 4 }
}
}
]
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
);
}
catch (e) {
print(e);
}

The operation returns the following:

{
"acknowledged" : true,
"deletedCount" : 1,
"insertedCount" : 2,
"matchedCount" : 2,
"upsertedCount" : 0,
"insertedIds" : {
"0" : 4,
"1" : 5
},
"upsertedIds" : {
}
}

For more examples, see bulkWrite() Examples

Strategies for Bulk Inserts to a Sharded Collection


Large bulk insert operations, including initial data inserts or routine data import, can affect
sharded cluster performance. For bulk inserts, consider the following strategies:

Pre-Split the Collection

If the sharded collection is empty, then the collection has only one initial chunk, which
resides on a single shard. MongoDB must then take time to receive data, create splits, and
distribute the split chunks to the available shards. To avoid this performance cost, you can
pre-split the collection, as described in Split Chunks in a Sharded Cluster.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Unordered Writes to mongos

To improve write performance to sharded clusters, use bulkWrite() with the optional
parameter ordered set to false. mongos can attempt to send the writes to multiple shards
simultaneously. For empty collections, first pre-split the collection as described in Split
Chunks in a Sharded Cluster.

Avoid Monotonic Throttling

If your shard key increases monotonically during an insert, then all inserted data goes to the
last chunk in the collection, which will always end up on a single shard. Therefore, the
insert capacity of the cluster will never exceed the insert capacity of that single shard.

If your insert volume is larger than what a single shard can process, and if you cannot avoid
a monotonically increasing shard key, then consider the following modifications to your
application:

 Reverse the binary bits of the shard key. This preserves the information and avoids
correlating insertion order with increasing sequence of values.
 Swap the first and last 16-bit words to "shuffle" the inserts.

Example

The following example, in C++, swaps the leading and trailing 16-bit word of BSON
ObjectIds generated so they are no longer monotonically increasing.

using namespace mongo;


OID make_an_id() {
OID x = OID::gen();
const unsigned char *p = x.getData();
swap( (unsigned short&) p[0], (unsigned short&) p[10] );
return x;
}
void foo() {
// create an object
BSONObj o = BSON( "_id" << make_an_id() << "x" << 3 << "name" << "jane" );
// now we may insert o into a sharded collection
}
Tip
See also:
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Shard Keys for information on choosing a sharded key. Also see Shard Key Internals (in
particular, Choose a Shard Key).

Retryable Writes
New in version 3.6.

Retryable writes allow MongoDB drivers to automatically retry certain write operations a
single time if they encounter network errors, or if they cannot find a healthy primary in the
replica sets or sharded cluster. [1]

Prerequisites
Retryable writes have the following requirements:

Supported Deployment Topologies


Retryable writes require a replica set or sharded cluster, and do not support
standalone instances.
Supported Storage Engine
Retryable writes require a storage engine supporting document-level locking, such
as the WiredTiger or in-memory storage engines.
3.6+ MongoDB Drivers

Clients require MongoDB drivers updated for MongoDB 3.6 or greater:

Java 3.6+ C# 2.5+ Perl 2.0+

Python 3.6+Node 3.0+PHPC 1.4+

C 1.9+ Ruby 2.5+Scala 2.2+


MongoDB Version
The MongoDB version of every node in the cluster must be 3.6 or greater, and the
featureCompatibilityVersion of each node in the cluster must be 3.6 or
greater. See setFeatureCompatibilityVersion for more information on the
featureCompatibilityVersion flag.
Write Acknowledgment
Write operations issued with a Write Concern of 0 are not retryable.

Retryable Writes and Multi-Document Transactions


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
New in version 4.0.

The transaction commit and abort operations are retryable write operations. If the commit
operation or the abort operation encounters an error, MongoDB drivers retry the operation a
single time regardless of whether retryWrites is set to false.

The write operations inside the transaction are not individually retryable, regardless of
value of retryWrites.

For more information on transactions, see Transactions.

Enabling Retryable Writes


MongoDB Drivers
MongoDB 3.6 introduced support for Retryable Writes, but most official MongoDB
3.6 and 4.0-compatible drivers disabled this feature by default. For such drivers,
retryable writes could be enabled per connection by including the
retryWrites=true option in the connection string for that connection. Refer to
the MongoDB Driver Documentation to determine the correct default state of
retryWrites for your specific driver and version.The official MongoDB 4.2+
compatible drivers enable Retryable Writes by default. Applications upgrading to
the 4.2+ compatible drivers that require retryable writes may omit the
retryWrites=true option. Applications upgrading to the 4.2+ compatible drivers
that require disabling retryable writes must include retryWrites=false in the
connection string.
mongosh

To enable retryable writes in mongosh, use the --retryWrites command line


option:

mongosh --retryWrites

Retryable Write Operations


The following write operations are retryable when issued with acknowledged write
concern; e.g., Write Concern cannot be {w: 0}.

Note

The write operations inside the transactions are not individually retryable.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Methods Descriptions
db.collection.insertOne()
db.collection.insertMany() Insert operations.
db.collection.updateOne()
db.collection.replaceOne() Single-document update operations. [1]
db.collection.deleteOne()
db.collection.remove() where justOne Single document delete operations.
is true
db.collection.findAndModify() findAndModify operations. All
db.collection.findOneAndDelete()
db.collection.findOneAndReplace() findAndModify operations are single
db.collection.findOneAndUpdate() document operations.
db.collection.bulkWrite() with the
following write operations: Bulk write operations that only consist of the
single-document write operations. A retryable
 insertOne bulk operation can include any combination of
 updateOne the specified write operations but cannot
 replaceOne include any multi-document write operations,
 deleteOne such as updateMany.

Bulk write operations that only consist of the


Bulk operations for: single-document write operations. A retryable
bulk operation can include any combination of
 Bulk.find.removeOne()
the specified write operations but cannot
 Bulk.find.replaceOne()
 Bulk.find.replaceOne() include any multi-document write operations,
such as update which specifies true for the
multi option.
Note
Updates to Shard Key Values

Starting in MongoDB 4.2, you can update a document's shard key value (unless the shard
key field is the immutable _id field) by issuing single-document update/findAndModify
operations either as a retryable write or in a transaction. For details, see Change a
Document's Shard Key Value.

(1, 2) MongoDB 4.2 will retry certain single-document upserts (update with upsert:
true and multi: false) that encounter a duplicate key exception. See Duplicate Key
[1]
Errors on Upsert for conditions.Prior to MongoDB 4.2, MongoDB would not retry
upsert operations that encountered a duplicate key error.

Behavior
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Persistent Network Errors

MongoDB retryable writes make only one retry attempt. This helps address transient
network errors and replica set elections, but not persistent network errors.

Failover Period

If the driver cannot find a healthy primary in the destination replica set or sharded cluster
shard, the drivers wait serverSelectionTimeoutMS milliseconds to determine the new
primary before retrying. Retryable writes do not address instances where the failover period
exceeds serverSelectionTimeoutMS.

Warning

If the client application becomes temporarily unresponsive for more than the
localLogicalSessionTimeoutMinutes after issuing a write operation, there is a chance
that when the client applications starts responding (without a restart), the write operation
may be retried and applied again.

Duplicate Key Errors on Upsert

MongoDB 4.2 will retry single-document upsert operations (i.e upsert : true and multi
: false) that fail due to a duplicate key error only if the operation meets all of the
following conditions:

 The target collection has a unique index that caused the duplicate key error.

 The update match condition is either:


o A single equality predicate

{ "fieldA" : "valueA" },

or

o a logical AND of equality predicates

{ "fieldA" : "valueA", "fieldB" : "valueB" }

 The set of fields in the unique index key pattern matches the set of fields in the
update query predicate.
 The update operation does not modify any of the fields in the query predicate.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
The following table contains examples of upsert operations that the server can or cannot
retry on a duplicate key error:

Unique
Index Key Update Operation Retryable
Pattern
db.collName.updateOne(
{ _id :
ObjectId("1aa1c1efb123f14aaa167aaa") },
{ _id : 1 }
{ $set : { fieldA : 25 } }, Yes
{ upsert : true }
)

db.collName.updateOne(
{ fieldA : { $in : [ 25 ] } },
{ fieldA :
{ $set : { fieldB : "someValue" } },
1} Yes
{ upsert : true }
)

db.collName.updateOne(
{
{ fieldA : 25, fieldB : "someValue" },
fieldA : 1,
{ $set : { fieldC : false } },
fieldB : 1 Yes
{ upsert : true }
}
)

db.collName.updateOne(
{ fieldA : { $lte : 25 } }, No
{ fieldA :
{ $set : { fieldC : true } },
1}
{ upsert : true } The query predicate on fieldA is
) not an equality

db.collName.updateOne(
{ fieldA : { $in : [ 25 ] } }, No
{ fieldA :
{ $set : { fieldA : 20 } },
1} The update operation modifies
{ upsert : true } fields specified in the query
) predicate.

{ _id : 1 } db.collName.updateOne( No
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Unique
Index Key Update Operation Retryable
Pattern
{ fieldA : { $in : [ 25 ] } },
{ $set : { fieldA : 20 } },
{ upsert : true } The set of query predicate fields
) (fieldA) does not match the set of
index key fields (_id).
db.collName.updateOne( No
{ fieldA : 25, fieldC : true },
{ fieldA :
{ $set : { fieldD : false } }, The set of query predicate fields
1}
{ upsert : true } (fieldA, fieldC) does not match
) the set of index key fields
(fieldA).

Prior to MongoDB 4.2, MongoDB retryable writes did not support retrying upserts which
failed due to duplicate key errors.

Diagnostics

New in version 3.6.3.

The serverStatus command, and its mongosh shell helper db.serverStatus() includes
statistics on retryable writes in the transactions section.

Retryable Writes Against local Database

The official MongoDB 4.2-series drivers enable retryable writes by default. Applications
which write to the local database will encounter write errors upon upgrading to 4.2-series
drivers unless retryable writes are explicitly disabled.

To disable retryable writes, specify retryWrites=false in the connection string for the
MongoDB cluster.

Retryable Reads
Retryable reads allow MongoDB drivers to automatically retry certain read operations a
single time if they encounter certain network or server errors.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Prerequisites
Minimum Driver Version

Official MongoDB drivers compatible with MongoDB Server 4.2 and later support
retryable reads.

For more information on official MongoDB drivers, see MongoDB Drivers.

Minimum Server Version


Drivers can only retry read operations if connected to MongoDB Server 3.6 or later.

Enabling Retryable Reads


Official MongoDB drivers compatible with MongoDB Server 4.2 and later enable retryable
reads by default. To explicitly disable retryable reads, specify retryReads=false in the
connection string for the deployment.

mongosh does not support retryable reads.

Retryable Read Operations


MongoDB drivers support retrying the following read operations. The list references a
generic description of each method. For specific syntax and usage, defer to the driver
documentation for that method.

Methods Descriptions
Collection.aggregate
Collection.count
Collection.countDocuments
Collection.distinct
Collection.estimatedDocumentCount
Collection.find CRUD API Read
Database.aggregate Operations

For Collection.aggregate and Database.aggregate, drivers can


only retry aggregation pipelines which do not include write stages, such
as $out or $merge.
Collection.watch
Database.watch
Change Stream
MongoClient.watch Operations
MongoClient.listDatabases Enumeration
Database.listCollections
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Methods Descriptions
Collection.listIndexes Operations
GridFS File
GridFS Operations backed by Collection.find (e.g.
Download
GridFSBucket.openDownloadStream)
Operations

MongoDB drivers may include retryable support for other operations, such as helper
methods or methods that wrap a retryable read operation. Defer to the driver documentation
to determine whether a method explicitly supports retryable reads.

Tip
See also:

Retryable Read Specification: Supported Read Operations

Unsupported Read Operations

The following operations do not support retryable reads:

 db.collection.mapReduce()
 getMore
 Any read command passed to a generic Database.runCommand helper, which is
agnostic about read or write commands.

Behavior
Persistent Network Errors

MongoDB retryable reads make only one retry attempt. This helps address transient
network errors or replica set elections, but not persistent network errors.

Failover Period

The driver performs server selection using the read command's original read preference
before retrying the read operation. If the driver cannot select a server for the retry attempt
using the original read preference, the driver returns the original error.

The drivers wait serverSelectionTimeoutMS milliseconds before performing server


selection. Retryable reads do not address instances where no eligible servers exist after
waiting serverSelectionTimeoutMS.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf

SQL to MongoDB Mapping Chart


In addition to the charts that follow, you might want to consider the Frequently Asked
Questions section for a selection of common questions about MongoDB.

Terminology and Concepts


The following table presents the various SQL terminology and concepts and the
corresponding MongoDB terminology and concepts.

SQL Terms/Concepts MongoDB Terms/Concepts


database database
table collection
row document or BSON document
column field
index index
table joins $lookup, embedded documents
primary key primary key

Specify any unique column or column combination In MongoDB, the primary key is
as primary key. automatically set to the _id field.
aggregation pipeline
aggregation (e.g. group by)
See the SQL to Aggregation Mapping
Chart.
$out

SELECT INTO NEW_TABLE See the SQL to Aggregation Mapping


Chart.
$merge (Available starting in
MongoDB 4.2)
MERGE INTO TABLE
See the SQL to Aggregation Mapping
Chart.
$unionWith (Available starting in
UNION ALL
MongoDB 4.4)
transactions transactions
Tip

For many scenarios, the denormalized data model (embedded documents and
arrays) will continue to be optimal for your data and use cases instead of
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
SQL Terms/Concepts MongoDB Terms/Concepts

multi-document transactions. That is, for many scenarios, modeling your data
appropriately will minimize the need for multi-document transactions.

Executables
The following table presents some database executables and the corresponding MongoDB
executables. This table is not meant to be exhaustive.

MongoDBMySQL Oracle Informix DB2


Database Servermongod mysqldoracle IDS DB2 Server
Database Client mongosh mysql sqlplusDB-AccessDB2 Client

Examples
The following table presents the various SQL statements and the corresponding MongoDB
statements. The examples in the table assume the following conditions:

 The SQL examples assume a table named people.

 The MongoDB examples assume a collection named people that contain


documents of the following prototype:

{
_id: ObjectId("509a8fb2f3f4948bd2f983a0"),
user_id: "abc123",
age: 55,
status: 'A'
}
Create and Alter

The following table presents the various SQL statements related to table-level actions and
the corresponding MongoDB statements.

SQL Schema Statements MongoDB Schema Statements


CREATE TABLE people ( Implicitly created on first insertOne() or insertMany()
id MEDIUMINT NOT NULL operation. The primary key _id is automatically added if _id
AUTO_INCREMENT, field is not specified.
user_id Varchar(30),
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
SQL Schema Statements MongoDB Schema Statements
db.people.insertOne( {
user_id: "abc123",
age Number, age: 55,
status char(1), status: "A"
PRIMARY KEY (id) })
) However, you can also explicitly create a collection:

db.createCollection("people")

Collections do not describe or enforce the structure of its


documents; i.e. there is no structural alteration at the
collection level.

However, at the document level, updateMany() operations


ALTER TABLE people can add fields to existing documents using the $set operator.
ADD join_date DATETIME
db.people.updateMany(
{ },
{ $set: { join_date: new Date() } }
)

Collections do not describe or enforce the structure of its


documents; i.e. there is no structural alteration at the
collection level.

However, at the document level, updateMany() operations


ALTER TABLE people can remove fields from documents using the $unset
DROP COLUMN join_date operator.

db.people.updateMany(
{ },
{ $unset: { "join_date": "" } }
)

CREATE INDEX
idx_user_id_asc db.people.createIndex( { user_id: 1 } )
ON people(user_id)

CREATE INDEX db.people.createIndex( { user_id: 1, age: -1 } )


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
SQL Schema Statements MongoDB Schema Statements
idx_user_id_asc_age_desc
ON people(user_id, age
DESC)

DROP TABLE people db.people.drop()

For more information on the methods and operators used, see:

 db.collection.insertOne()
 db.collection.insertMany()
 db.createCollection()
 db.collection.updateMany()
 db.collection.createIndex()
 db.collection.drop()
 $set
 $unset

Tip
See also:

 Databases and Collections


 Documents
 Indexes
 Data Modeling Concepts.

Insert

The following table presents the various SQL statements related to inserting records into
tables and the corresponding MongoDB statements.

SQL INSERT Statements MongoDB insertOne() Statements


INSERT INTO people(user_id,
age,
db.people.insertOne(
status)
{ user_id: "bcd001", age: 45, status: "A" }
VALUES ("bcd001",
)
45,
"A")
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
For more information, see db.collection.insertOne().

Tip
See also:

 Insert Documents
 db.collection.insertMany()
 Databases and Collections
 Documents

Select

The following table presents the various SQL statements related to reading records from
tables and the corresponding MongoDB statements.

Note

The find() method always includes the _id field in the returned documents unless
specifically excluded through projection. Some of the SQL queries below may include an
_id field to reflect this, even if the field is not included in the corresponding find() query.

SQL SELECT Statements MongoDB find() Statements


SELECT *
db.people.find()
FROM people

SELECT id, db.people.find(


user_id, { },
status { user_id: 1, status: 1 }
FROM people )

db.people.find(
SELECT user_id, status { },
FROM people { user_id: 1, status: 1, _id: 0 }
)

SELECT * db.people.find(
FROM people { status: "A" }
WHERE status = "A" )

SELECT user_id, status db.people.find(


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
SQL SELECT Statements MongoDB find() Statements
{ status: "A" },
FROM people
{ user_id: 1, status: 1, _id: 0 }
WHERE status = "A"
)

SELECT * db.people.find(
FROM people { status: { $ne: "A" } }
WHERE status != "A" )

SELECT * db.people.find(
FROM people { status: "A",
WHERE status = "A" age: 50 }
AND age = 50 )

SELECT *
db.people.find(
FROM people
{ $or: [ { status: "A" } , { age: 50 } ] }
WHERE status = "A"
)
OR age = 50

SELECT * db.people.find(
FROM people { age: { $gt: 25 } }
WHERE age > 25 )

SELECT * db.people.find(
FROM people { age: { $lt: 25 } }
WHERE age < 25 )

SELECT *
db.people.find(
FROM people
{ age: { $gt: 25, $lte: 50 } }
WHERE age > 25
)
AND age <= 50

SELECT * db.people.find( { user_id: /bc/ } )


-or-
FROM people
WHERE user_id like "%bc%" db.people.find( { user_id: { $regex: /bc/ } } )

SELECT * db.people.find( { user_id: /^bc/ } )


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
SQL SELECT Statements MongoDB find() Statements
-or-
FROM people
WHERE user_id like "bc%" db.people.find( { user_id: { $regex: /^bc/ } } )

SELECT *
FROM people
db.people.find( { status: "A" } ).sort( { user_id: 1 } )
WHERE status = "A"
ORDER BY user_id ASC

SELECT *
FROM people
db.people.find( { status: "A" } ).sort( { user_id: -1 } )
WHERE status = "A"
ORDER BY user_id DESC

db.people.count()
SELECT COUNT(*) or
FROM people
db.people.find().count()

db.people.count( { user_id: { $exists: true } } )


SELECT COUNT(user_id) or
FROM people
db.people.find( { user_id: { $exists: true } } ).count()

SELECT COUNT(*) db.people.count( { age: { $gt: 30 } } )


or
FROM people
WHERE age > 30 db.people.find( { age: { $gt: 30 } } ).count()

db.people.aggregate( [ { $group : { _id : "$status" } } ] )


SELECT DISTINCT(status) or, for distinct value sets that do not exceed the BSON size
limit
FROM people
db.people.distinct( "status" )

SELECT * db.people.findOne()
FROM people or
LIMIT 1
db.people.find().limit(1)
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
SQL SELECT Statements MongoDB find() Statements

SELECT *
FROM people
db.people.find().limit(5).skip(10)
LIMIT 5
SKIP 10

EXPLAIN SELECT *
FROM people db.people.find( { status: "A" } ).explain()
WHERE status = "A"

For more information on the methods and operators used, see

 db.collection.find()
 db.collection.distinct()
 db.collection.findOne()
 limit()
 skip()
 explain()
 sort()
 count()
 $ne
 $and
 $or
 $gt
 $lt
 $exists
 $lte
 $regex

Tip
See also:

 Query Documents
 Query and Projection Operators
 mongosh Methods

Update Records

The following table presents the various SQL statements related to updating existing
records in tables and the corresponding MongoDB statements.
https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
SQL Update
MongoDB updateMany() Statements
Statements
db.people.updateMany(
UPDATE people
{ age: { $gt: 25 } },
SET status = "C"
{ $set: { status: "C" } }
WHERE age > 25
)

db.people.updateMany(
UPDATE people
{ status: "A" } ,
SET age = age + 3
{ $inc: { age: 3 } }
WHERE status = "A"
)

For more information on the method and operators used in the examples, see:

 db.collection.updateMany()
 $gt
 $set
 $inc

Tip
See also:

 Update Documents
 Update Operators
 db.collection.updateOne()
 db.collection.replaceOne()

Delete Records

The following table presents the various SQL statements related to deleting records from
tables and the corresponding MongoDB statements.

SQL Delete Statements MongoDB deleteMany() Statements


DELETE FROM people
db.people.deleteMany( { status: "D" } )
WHERE status = "D"

DELETE FROM people db.people.deleteMany({})

For more information, see db.collection.deleteMany().


https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/
https://docplayer.es/65876820-Taller-mongodb-1er-cuatrimestre-2016-base-de-
datos.html
https://disi.unal.edu.co/~eleonguz/cursos/bda/talleres/Mongo/TallerMongoDB.pdf
https://www.editorialuoc.cat/media/resources/public/9b/
9b67/9b67f646f5ea457d811b0afba5f5e2a6.pdf
Tip
See also:

 Delete Documents
 db.collection.deleteOne()

Further Reading
If you are considering migrating your SQL application to MongoDB, download the
MongoDB Application Modernization Guide.

The download includes the following resources:

 Presentation on the methodology of data modeling with MongoDB


 White paper covering best practices and considerations for migrating to MongoDB
from an RDBMS data model
 Reference MongoDB schema with its RDBMS equivalent
 Application Modernization scorecard

You might also like