MongoDB -Document Operations
Data Types | Description |
---|---|
String | String is the most commonly used datatype. It is used to store data |
Integer | Integer is used to store the numeric value. It can be 32 bit or 64 bit depends on server |
Boolean | This datatype is used to store boolean values. It just shows YES/NO values. |
Double | Double datatype stores floating point values. |
Min/Max Keys | This datatype compare a value against the lowest and highest bson elements. |
Arrays | This datatype is used to store a list or multiple values into a single key. |
Object | Object datatype is used for embedded documents. |
Null | It is used to store null values. |
Symbol | It is generally used for languages that use a specific type. |
Date | This datatype stores the current date or time in unix time format |
1.Insert Documents
MongoDB provides the following methods for inserting documents into a collection:
-
db.collection.insert()
-
db.collection.insertOne()
-
db.collection.insertMany()
If the collection does not currently exist, insert operations will create the collection.
_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.
1.db.collection.insert():
Inserts a single document or multiple documents into a collection. To insert a single document, pass a document to the method; to insert multiple documents, pass an array of documents to the method
db.users.insert(
{
username: "Satya",
password: "Satya@134",
age:27,
status:"active"
}
)
WriteResult({ "nInserted" : 1 })
2.db.collection.insertOne()
Inserts a single document into a collection
> db.users.insertOne(
{
username: "Smlcodes",
password: "Smlcodes@134",
age:27,
status:"active"
}
)
{
"acknowledged" : true,
"insertedId" : ObjectId("58986791fb8a774546289da0")
}
3.db.collection.insertMany()
Inserts multiple documents into a collection.
db.users.insertMany(
[
{ username:"Surya", password:"Password@1345", age: 42, status: "inactive", },
{ username:"Ravi", password:"Password@1345", age: 22, status: "inactive", },
{ username:"Rakesh", password:"Password@1345", age: 34, status: "active", }
]
)
----
... )
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("589868c4fb8a774546289da1"),
ObjectId("589868c4fb8a774546289da2"),
ObjectId("589868c4fb8a774546289da3")
]
}
2.Query Documents (find Operations)
MongoDB provides the db.collection.find() method to read documents from a collection. The db.collection.find() method returns a cursor to the matching documents.
Syntax **> db.collection.find(
-
**
:** a query filter to specify which documents to return. -
< projection>: which fields from the matching documents to return
1.Select All Documents in a Collection
An empty query filter document ({}) selects all documents in the collection
Syntax > db.users.find( {} ) or db.users.find()
> db.users.find({})
{ "_id" : ObjectId("58986156fb8a774546289d9e"), "username" : "admin", "password" : "Admin@123" }
{ "_id" : ObjectId("58986716fb8a774546289d9f"), "username" : "Satya", "password" : "Satya@134", "age" : 27, "status" : "active" }
{ "_id" : ObjectId("58986791fb8a774546289da0"), "username" : "Smlcodes", "password" : "Smlcodes@134", "age" : 27, "status" : "active" }
{ "_id" : ObjectId("589868c4fb8a774546289da1"), "username" : "Surya", "password" : "Password@1345", "age" : 42, "status" : "inactive" }
2.Select All Documents with Condition
> db.users.find( { status: "active" } )
{ "_id" : ObjectId("58986716fb8a774546289d9f"), "username" : "Satya", "password" : "Satya@134", "age" : 27, "status" : "active" }
{ "_id" : ObjectId("58986791fb8a774546289da0"), "username" : "Smlcodes", "password" : "Smlcodes@134", "age" : 27, "status" : "active" }
{ "_id" : ObjectId("589868c4fb8a774546289da3"), "username" : "Rakesh", "password" : "Password@1345", "age" : 34, "status" : "active" }
3.Select All Documents with AND Condition
We can specify the the no. of conditions by using comma (,) operator
Retrieves all documents where status equals “active” and age is less than ($lt) 30:
> db.users.find( { status: "active", age: { $lt: 30 } } )
{ "_id" : ObjectId("58986716fb8a774546289d9f"), "username" : "Satya", "password" : "Satya@134", "age" : 27, "status" : "active" }
{ "_id" : ObjectId("58986791fb8a774546289da0"), "username" : "Smlcodes", "password" : "Smlcodes@134", "age" : 27, "status" : "active" }
4.Select All Documents with OR Condition
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.
Retrieves all documents where the status equals “inactive” or age is less than ($lt) 30:
db.users.find(
{
$or: [ { status: "inactive" }, { age: { $lt: 30 } } ]
}
)
-------
{ "_id" : ObjectId("58986716fb8a774546289d9f"), "username" : "Satya", "password" : "Satya@134", "age" : 27, "status" : "active" }
{ "_id" : ObjectId("589868c4fb8a774546289da1"), "username" : "Surya", "password" : "Password@1345", "age" : 42, "status" : "inactive" }
For more related Query Documents visit MongoDB Offcial website
3.Update Documents
MongoDB provides the following methods for updating documents in a collection
-
db.collection.update()
-
db.collection.updateOne()
-
db.collection.updateMany()
-
db.collection.replaceOne()
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.
1.db.collection.update()
Either updates or replaces a single document that match a specified filter or updates all documents that match a specified filter.
db.users.update(
{ "status": "inactive" },
{
$set: { "Level": 2}
}
)
------
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
2.db.collection.updateOne()
Updates at most a single document that match a specified filter even though multiple documents may match the specified filter.
db.users.updateOne(
{ "username": "Surya" },
{
$set: { "password": "901290190", age: 20 }
}
)
------
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
3.db.collection.updateMany()
Update all documents that match a specified filter.
db.users.updateMany(
{ "status": "active" },
{
$set: { "Level": 1}
}
)
----------
{ "acknowledged" : true, "matchedCount" : 6, "modifiedCount" : 6 }
4.db.collection.replaceOne()
Replaces at most a single document that match a specified filter even though multiple documents may match the specified filter.
4.Delete Documents
MongoDB provides the following methods to delete documents of a collection:
-
db.collection.remove()
-
db.collection.deleteOne()
-
db.collection.deleteMany()
Delete operations do not drop indexes, even if deleting all documents from a collection
1.db.collection.remove()
To remove all documents from the collection based on condition
> db.users.remove( { age: 27 } )
WriteResult({ "nRemoved" : 2 })
2.db.collection.deleteOne()
Delete at most a single document that match a specified filter,even though multiple documents may match
> db.users.deleteOne( { status: "active" } )
"acknowledged" : true, "deletedCount" : 1 }
3.db.collection.deleteMany()
To remove all documents from the collection based on condition
> db.users.deleteMany({ status : "inactive" })
"acknowledged" : true, "deletedCount" : 5 }
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.findOneAndModify().
-
db.collection.findOneAndModify() provides a sort option. The option allows for the deletion of the first document sorted by the specified order.
-
db.collection.bulkWrite().