MongoDB tutorials

2. Insert and read documents

Video tutorial:

So in MongoDB, we do not have database schema as we have in MySQL. Like we have tables in MySQL, we have collections in MongoDB. And like we have rows in MySQL tables, we have documents in MongoDB collection and each document can further have documents inside it, we call it “nested documents”. Like MySQL has relations between 2 documents, in MongoDB, all related data should be put inside that document. For example, if a user has friends then no need to create a separate collection for friends. You can store all his friends inside the user’s document object. That makes the MongoDB fast as compared to MySQL because it has less number of queries as in MySQL.

What is collection

A collection is an entity, like a user, products, etc. And documents are the actual data in those collections like the user has the name “adnan”, age is “29” etc.

In MongoDB, the data is stored in JSON format. It has arrays and objects. To create a collection, you have to call a function named createCollection. Suppose you want to create a collection for users, then the command would be:

db.createCollection("users")

db is an built-in object in MongoDB. If all goes well, you will the following output:

mongodb create collection

Now you will see an ok message if the collection is successfully created. Now we need to add data in this collection. We have a function named “insert” and it accepts a Javascript object as a parameter which will be saved in the database. Run the following command to insert one document:

db.users.insert({"name": "Adnan", "age": 27})

Now you need to view the database data. You can run the following command to view all collections in a database:

show collections

And you can run the following command to get all record from users collection:

db.users.find()

You will see an ObjectId along with other fields. That is the unique ID set by MongoDB server for each document while adding. Now to delete all record from MongoDB collection, you can call a function named drop. Suppose, you want to delete all data from users collection:

db.users.drop()

In the next video from this MongoDB tutorials series, we will discuss complex queries. Using AND and OR operator, less than, greater than and equal to clauses.