MongoDB CRUD Operations
MongoDB CRUD Operations
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
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.
In MongoDB, insert operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.
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
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:
You can specify criteria, or filters, that identify the documents to update. These filters use
the same syntax as read operations.
Delete Operations
Delete operations remove documents from a collection. MongoDB provides the following
methods to delete documents of a collection:
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.
Insert Documents
➤ Use the Select your language drop-down menu in the upper-right to set the language of
the examples on this page.
Note
Creating a Collection
If the collection does not currently exist, insert operations will create the 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" } }
)
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" } )
➤ Use the Select your language drop-down menu in the upper-right to set the language of
the examples on this page.
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" } }
])
insertMany() returns a document that includes the newly inserted documents _id field
values. See the reference for an example.
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.
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 more information on the MongoDB Compass query bar, see Query Bar.
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" }
The MongoDB Compass query bar autocompletes the current query based on the keys in
your collection's documents, including keys in embedded sub-documents.
Copy the following filter into the Compass query bar and click Find:
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 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:
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:
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:
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.
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
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.
➤ Use the Select your language drop-down menu in the upper-right to set the language of
the following examples.
[
{ 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 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:
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:
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" }
A query filter document can use the query operators to specify conditions in the following
form:
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 } }
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:
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 ] }
]);
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:
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:
The following example queries for all documents where tags is an array that contains the
string "red" as one of its elements:
To specify conditions on the elements in the array field, use query operators in the query
filter document:
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.
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:
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:
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:
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 } } )
Query Documents
Query on Embedded/Nested 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 } ] }
]);
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:
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:
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:
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:
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:
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:
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
➤ 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 } ] }
]);
With the exception of the _id field, you cannot combine inclusion and exclusion statements
in projection documents.
With the exception of the _id field, you cannot combine inclusion and exclusion statements
in projection documents.
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 } }.
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 } }.
The following example uses the $slice projection operator to return the last element in the
instock array:
$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
←
➤ 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 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.
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();
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) :
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 query only returns the document that does not contain the item field.
Tip
See also:
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.
The following examples describe ways to manually iterate the cursor to access the
documents or to use the iterator index.
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:
You can also use the cursor method next() to access the documents, as in the following
example:
You can use the cursor method forEach() to iterate the cursor and access the documents,
as in the following example:
(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:
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.
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 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:
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().
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:
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
{
"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.
IMongoCollection.UpdateOne()
IMongoCollection.UpdateMany()
IMongoCollection.ReplaceOne()
inventory
inventory
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
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.
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.
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:
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
$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") }
])
db.students.find()
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.
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") },
])
db.students2.find()
db.students2.updateMany( {},
[
{ $replaceRoot: { newRoot:
{ $mergeObjects: [ { quiz1: 0, quiz2: 0, test1: 0, test2: 0 }, "$$ROOT" ] }
} },
{ $set: { modified: "$$NOW"} }
]
)
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") }
] );
db.students3.find()
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"
}}}}
]
)
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.
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()
db.students4.updateOne( { _id: 2 },
[ { $set: { quizzes: { $concatArrays: [ "$quizzes", [ 8, 6 ] ] } } } ]
)
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 ] }
])
db.temperatures.find()
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.
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:
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.
IMongoCollection.DeleteMany()
IMongoCollection.DeleteOne()
The examples on this page use the inventory collection. To populate the inventory
collection, run the following:
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:
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":
The following example deletes the first document where status is "D":
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:
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.bulkWrite().
See the individual reference pages for the methods for more information and examples.
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.
bulkWrite() Methods
bulkWrite() supports the following write operations:
insertOne
updateOne
updateMany
replaceOne
deleteOne
deleteMany
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);
}
{
"acknowledged" : true,
"deletedCount" : 1,
"insertedCount" : 2,
"matchedCount" : 2,
"upsertedCount" : 0,
"insertedIds" : {
"0" : 4,
"1" : 5
},
"upsertedIds" : {
}
}
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.
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.
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:
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.
mongosh --retryWrites
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.
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.
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.
{ "fieldA" : "valueA" },
or
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
The serverStatus command, and its mongosh shell helper db.serverStatus() includes
statistics on retryable writes in the transactions section.
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.
Methods Descriptions
Collection.aggregate
Collection.count
Collection.countDocuments
Collection.distinct
Collection.estimatedDocumentCount
Collection.find CRUD API Read
Database.aggregate 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:
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.
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
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.
Examples
The following table presents the various SQL statements and the corresponding MongoDB
statements. The examples in the table assume the following conditions:
{
_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.
db.createCollection("people")
db.people.updateMany(
{ },
{ $unset: { "join_date": "" } }
)
CREATE INDEX
idx_user_id_asc db.people.createIndex( { user_id: 1 } )
ON people(user_id)
db.collection.insertOne()
db.collection.insertMany()
db.createCollection()
db.collection.updateMany()
db.collection.createIndex()
db.collection.drop()
$set
$unset
Tip
See also:
Insert
The following table presents the various SQL statements related to inserting records into
tables and the corresponding MongoDB statements.
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.
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 * 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 *
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()
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"
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.
Delete Documents
db.collection.deleteOne()
Further Reading
If you are considering migrating your SQL application to MongoDB, download the
MongoDB Application Modernization Guide.