MongoDB Basics & CRUD Operations

MongoDB Basics & CRUD Operations

·

8 min read

MongoDB Basics

As we know, that mongoDB is no sql database and it store in data in BSON documents. Here, BSON stands for binary representation of JSON documents, although BSON contains more data types as compared to JSON. Databases, collections, documents are important parts of MongoDB without them you are not able to store data on the MongoDB server.

Naming restriction for database, collection and fields are :

  1. Database name can not start with special character.
  2. MongoDB database names cannot be empty and must contain less than 64 characters.
  3. Collection name must starts with an underscore or a character.
  4. The maximum length of the collection name is 120 bytes(including the database name, dot separator, and the collection name).
  5. The field names are of strings.

Document Size

The maximum size of the BSON document is 16MB. It ensures that the single document does not use too much amount of RAM or bandwidth(during transmission). If a document contains more data than the specified size, then MongoDB provides a GridFS API to store such type of documents.

MongoDB Cursor

According to MongoDB, cursor means that when you run a query in mongo shell then it return a cursor at the end of document which point out to that document. This is known as cursor. Or in other words we can say that a cursor is a pointer, and using this pointer we can access the document. mongo1.jpg

  • By default, cursor iterate automatically, but you can iterate a cursor manually also using javascript in mongo shell. mongo2.jpg

    Data types in MongoDB

    According to current version of mongoDB, there are 18 data types are defined :-
  1. String : This is commonly used data type and basically BSON strings are of UTF-8. So, the drivers for each programming language convert from the string format of the language to UTF-8 while serializing and de-serializing BSON. The string must be a valid UTF-8. string.jpg
  2. Integer : In MongoDB, the integer data type is used to store an integer value. We can store integer data type in two forms 32 -bit signed integer and 64 – bit signed integer. integer.jpg
  3. Double : The double data type is used to store the floating-point values. double.jpg
  4. Boolean : The boolean data type is used to store either true or false. boolean.jpg
  5. Null : The null data type is used to store the null value. null.jpg
  6. undefined : This data type stores the undefined values. And some mongo driver treat as null value or some treat as undefined. undefined.jpg
  7. Array : The Array is the set of values. It can store the same or different data types values in it. In MongoDB, the array is created using square brackets([]). array.jpg
  8. Object : Object data type stores embedded documents. Embedded documents are also known as nested documents. Embedded document or nested documents are those types of documents which contain a document inside another document. object.jpg
  9. BsonRegExp: This datatype is used to store regular expressions. regex.jpg
  10. Date: Date data type stores date. It is a 64-bit integer which represents the number of milliseconds. BSON data type generally supports UTC datetime and it is signed. If the value of the date data type is negative then it represents the dates before 1970. There are various methods to return date, it can be returned either as a string or as a date object. Some method for the date:
    • Date(): It returns the current date in string format.
    • new Date(): Returns a date object. Uses the ISODate() wrapper.
    • new ISODate(): It also returns a date object. Uses the ISODate() wrapper. date.jpg
  11. Min Key: Min key compares the value of the lowest BSON element
  12. Max Key : Max key compares the value against the highest BSON element. Both Min & Max key are internal data types.
  13. ObjectId : Whenever we create a new document in the collection MongoDB automatically creates a unique object id for that document(if the document does not have it). There is an _id field in MongoDB for each document. The data which is stored in Id is of hexadecimal format and the length of the id is 12 bytes which consist:
    • 4-bytes for Timestamp value.
    • 5-bytes for Random values. i.e., 3-bytes for machine Id and 2-bytes for process Id.
    • 3- bytes for Counter You can also create your own id field, but make sure that the value of that id field must be unique. ObjectId.jpg
  14. BsonSymbol: This data type similar to the string data type. It is generally not supported by a mongo shell, but if the shell gets a symbol from the database, then it converts this type into a string type.
  15. Timestamp : In MongoDB, this data type is used to store a timestamp. Basically this datatype is assigned when we use createdAt or updatedAt field in our document.
  16. Decimal : This MongoDB data type store 128-bit decimal-based floating-point value. This data type was introduced in MongoDB version 3.4 decimal.jpg
  17. Code: This datatype is used to store JavaScript code into the document without the scope. js-code.jpg
  18. Binary : This datatype is used to store binary data. And most of the use case is that when we want to store any file, image or non text data then that time we use this datatype. binary.jpg

Lets start with some basic mongo shell queries.

1. Create a New Database :

You can create a new Database in MongoDB by using “use Database_Name” command. The command creates a new database if it doesn’t exist, otherwise, it will return the existing database.you can run this command in mongo shell to create a new database. Your newly created database is not present in the list of Database. To display database, you need to insert at least one document into it. syntax :

use Database_name

create-db.jpg

2. Show list of Databases :

You can check currently selected database, using the command “show dbs“. Your newly created database is not present in the list of Database. To display any database, you need to insert at least one or more document into it. syntax

show dbs

list-of-dbs.jpg

3. Check current Database :

You can check list of databases, using the command “db” syntax

db

db.jpg

4. Switch to other Database :

You can switch to other database using the command “use Database_Name“. If Database does not exists then it will create a new Database.

5. Drop database :

we can drop the database using command dropDatabase. "db.dropDatabase()" the command is used to drop an existing database. This command will delete the currently selected database. If you have not selected any database, then it will delete the default ‘test’ database. syntax

db.dropDatabase()

drop.jpg

Crud operation in mongo shell

Basically, the CRUD (create, read, update and delete) means to perform basic query operation of database.

Create operations :

The create or insert operations are used to insert or add new documents in the collection. If a collection does not exist, then it will create a new collection in the database. You can perform, create operations using the following methods provided by the MongoDB:

  1. InsertOne() method : - it is used to insert a single document in the collection. syntax
    db.collection_name.insertOne()
    
    insert-One.jpg
  2. InsertMany() method : - it is used to insert multiple document in the collection. syntax
    db.collection_name.insertMany()
    
    insert-Many.jpg

Read operations :

The Read operations are used to retrieve documents from the collection, or in other words, read operations are used to query a collection for a document. You can perform read operation using the following method provided by the MongoDB:

  1. findOne() method : - it is used to find the single document from the collection on the basis of specified criteria. syntax
     db.collection_name.findOne()
    
    findOne.jpg In this example i search the document on the basis of field name
  2. find() method : - it is used to get all the document from the collection. syntax
     db.collection_name.find()
    
    find.jpg

Update operations:

The update operations are used to update or modify the existing document in the collection. You can perform update operations using the following methods provided by the MongoDB:

  1. UpdateOne() method :- It is used to update a single document in the collection that satisfy the given criteria. when we have to update any document then we have to use $set operator. For more details we will discuss in another blog where we particularly talk about update operations. syntax
    db.collection_name.updateOne({specified_criteria}, {data_to_update})
    
    update-One.jpg
  2. UpdateMany() method :- It is used to update multiple documents in the collection that satisfy the given criteria. syntax
      db.collection_name.updateMany({specified_criteria}, {data_to_update})
    
    update-Many.jpg
  3. ReplaceOne() method :- It is used to replace single document in the collection that satisfy the given criteria. syntax
      db.collection_name.replaceOne({specified_criteria}, {data_to_replace})
    
    replace-One.jpg

Delete operations :

The delete operation are used to delete or remove the documents from a collection. You can perform delete operations using the following methods provided by the MongoDB:

  1. DeleteOne() method :- It is used to delete a single document from the collection that satisfy the given criteria.
      db.collection_name.deleteOne({specified_criteria})
    
    delete-One.jpg
  2. DeleteMany() method :- It is used to delete multiple documents from the collection that satisfy the given criteria or if you pass empty object then it will delete all the document from the collection.
      db.collection_name.deleteMany({specified_criteria})
    
    delte-Many-All.jpg
  3. if you want to delete all the document from the collection then just pass empty object {} in the paranthesis. delte-Many.jpg

Thanks for reading, i will write more blogs on mongoDB where i will cover all the mongoDB queries from basic to advanced and if this blog got helpful to you then please like 👍 and share...