MongoDB: Basics with shell

In post MongoDB: Basic Installation we learn how to install MongoDB, and test that it is working expected or not.
Now in this post we’ll see

  • how to create database
  • collection
  • accessing documents from collection
  • other CRUD operations
  • and useful function using Mongo shell.

Connect  to MongoDB

Last step of previous post is to connecting to server after starting server.

It displays connecting to your default database, here test. Means everything working fine.

Creating Database

execute below command to create a database.

When you execute command use kode12, it return switched to db kode12. But make sure the database is not created yet.
MongoDB creates Database when you insert very first document in collection. you can check by below command.

It’ll shows only local database here.
Even MongoDB has not create any file on Physical Drive for DB kode12. You can see in below image.

Creating Collection and Insert Document

Use below command to insert a document to particular collection.

Note: We used db in above insert statement, because MongoDB allow us to refer in use Database by “db” so no need to write whole database name.

This command creates a Collection named “post” in database “kode12” and insert first document. You can also see Physical changes.

Retrieving Document

Method: find()

MySQL equivalent : SELECT * FROM post;

Command returns all document from collection post.

Note: in insert statement you inserted only 2 fields “title” and “author”, and while Retrieving you got another field “_id” which is added automatically by MongoDB. Which is a primary key.

For demo purpose i inserted another document.

Now find documents again, it’ll shows 2 documents.

Method: findOne()

MySQL equivalent : SELECT * FROM post LIMIT 1;
findOne method returns only first document from all returned document.
In our case.

Conditional Retrieval

You can use condition while retrieving documents. Suppose I want to get all post whose author is vishal.
MySQL equivalent : SELECT * FROM post where author=’vishal’;

Note: here I used pretty() at end of query, so do not confuse it used to format output in more readable format.

Here i covered basic select operation, in upcoming post you will get more on this.

Updating Document

MySQL equivalent: UPDATE post set author=’yogeshm’ WHERE title=’ 2. MongoDB Basics wit
h Shell’;

Use command to update record

View updated Record.

Removing Document

Conditional Removing
MySQL equivalent: DELETE FROM post WHERE author=’vishal’;
Use command

Remove all document.
MySQL equivalent: DELETE FROM post;
Use command

Drop Database

Use Command

It’ll remove all data from kode12 database,
Again

let’s look at back-end and check that physical changes done or not.