Mongodb Crud
Mongodb Crud
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.
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.
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.
Query Documents
Now we wil analyze the select queries using the db.collection.find()
method of mongoDB.
Selects documents in a collection or view and returns a cursor to the
selected documents.
Definition: db.collection.find(query, projection, options)
db.inventory.insertMany([
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm"
}, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in"
}, status: "A" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in"
}, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom:
"cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom:
"cm" }, status: "A" }
]);
$lt – Matches values that are less than the value specified in the
query.
$gte – Matches values that are greater than or equal to the value
specified in the query.
$lte – Matches values that are less than or equal to the value
specified in the query.
$ne – Matches all values that are not equal to the value specified in
the query.
$in – Matches any of the values that exist in an array specified in the
query.
$nin – Matches values that do not exist in an array specified in the
query.
$and – Joins query clauses with a logical AND returns all documents
that match the conditions of both clauses.
$not – Inverts the effect of a query expression and returns documents
that do not match the query expression.
$or – Joins query clauses with a logical OR returns all documents that
match the conditions of either clause.
$nor – Joins query clauses with a logical NOR returns all documents
that fail to match both clauses..
$all – Matches arrays that contain all elements specified in the query.
$elemMatch – Selects documents if an element in the array field
matches all the specified $elemMatch conditions.
$size – Selects documents if the array field is a specified size.
Projection operator
Specify OR Conditions
Using the $or operator, you can specify a compound query that joins
each clause with a logical OR conjunction so that the query selects
the documents in the collection that match at least one condition.
The following example retrieves all documents in the collection where
the status equals ”A” or qty is less than ($lt) 30:
db.inventory.find( { $or: [ { status: "A" }, { qty: {
$lt: 30 } } ] } )
The following query uses the less than operator ($lt) on the field h
embedded in the size field:
db.inventory.find( { "size.h": { $lt: 15 } } )
Query an Array
This page provides examples of query operations on array fields using
the db.collection.find() method in mongosh. The examples on this
page use the inventory collection. To populate the inventory
collection, run the following:
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [
14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [
14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"],
dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [
22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25
] }
]);
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"] } } )
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 } } )
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 } ] }
])
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 } )
$slice (projection)
The $slice projection operator specifies the number of elements in an
array to return in the query result.
The $slice has one of the following syntax forms:
db.collection.find(
<query>,
{ <arrayField>: { $slice: <number> } }
)
or
db.collection.find(
<query>,
{ <arrayField>: { $slice:
[ <number to skip>, <number to return> ] } }
)
the following operation projects the id field (by default), the qty field,
and the details field with just the specified slice of the colors array:
db.InvSliceTest.find( { },
{ qty: 1, "details.colors": { $slice: 1 } }
)
Examples
Let us considr the operations that query for null values using the
db.collection.find() method in mongosh.
The following examples use the inventory collection.
db.inventory.insertMany([
{ _id: 1, item: null },
{ _id: 2 }
])
Equality Filter
The { item : null } query matches documents that either contain the
item field whose value is null or that do not contain the item field.
db.inventory.find( { item: null } )
The query returns only the document where the item field has a value
of null.
Existence Check
The $exists is used for documents that do not contain a field.
The { item : { $exists: false } } query matches documents that do
not contain the item field.
db.inventory.find( { item : { $exists: false } } )
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()));
}
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)
Update Documents
We can use the following mongosh methods for updating the documents:
db.collection.updateOne(< filter >, < update >, < options >)
db.collection.updateMany(< filter >, < update >, < options >)
db.collection.replaceOne(< filter >, < update >, < options >)
{
<update operator>: { <field1>: <value1>, ... },
<update operator>: { <field2>: <value2>, ... },
...
}
db.inventory.updateMany(
{ "qty": { $lt: 50 } },
{
$set: { "size.uom": "in", status: "P" },
$currentDate: { lastModified: true }
}
)
db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 },
{ warehouse: "B", qty: 40 } ] }
)