MongoDB is No-Sql Open Source database system which uses
document as record of database.
MongoDB is designed for high performance and high accessibility.
Document is set of field => value pair combination and store
this information in form of BSON ( BSON is binary representation of JSON
records) which is native data type in most of languages.
MongoDB store set of documents in the form of collection.
Now let’s see the basic operations which can be handled in MongoDB.
- Create
- Read
- Update
- Delete
Collectively called CRUD operation
Create Operation
MongoDB perform atomic create operation on single document. It adds new document to selected collection.
db.{collection_name}.insert({
field => value,
field => value,
field => value,
});
Here value could be simple datatype or complex (document or
array)
Create operation always add unique identifier of
ObjectId data type to newly created document.
ObjectId is 12 byte BSON primarily used to maintain uniqueness in
collection. Following is byte structure of ObjectId.
- 4 byte for Unix epoch value
- 3 byte for machine identifier
- 2 byte for process identifier
- 3 byte for some random value
Example
db.user.insert({
name : “Zainul”,
email: zainabed@gmail.com,
address : "XYZ Address"
})
Read Operation
Read operation fetches documents from single or selected
collection. It uses projection and condition to modify resulting documents.
- Project is used to fetch only select fields of document which help to increase read operation.
- Condition is used to select particular document which falls under given condition.
db.{collection}.find(
{ condition },
{ projection }
)
We can use limit and sort to limit and order resulting
documents
Note: order of
resulting documents is not defined unless we provide order for documents
db.user.find(
{ name: ‘Zainul’ },
{ name : 1, email : 1}
)
Update Operation
Update operation modify existing document or even create new
document. It uses update criteria to isolate documents and update action to modify
values of selected documents.
db.{collection}.update(
{ update criteria },
{ update action },
{ update option }
)
Update option tells MongoDBto update multiple documents.
Example
db.user.update(
{ name : 'Zainul' },
{ $set : { name : "Abedin' } }
)
Note: use upsert to create a new document if that
document does not exist.
Delete Operation
Delete operation remove single or multiple documents from
selected collection. It uses remove criteria to identify the document which is
to be removed.
db.{collection}.remove(
{remove criteria}
)
db.use.remove(
{ name : 'Abedin' }
)
These basic operation will help to get started with MongoDB CRUD operation.
Comments
Post a Comment