Introduction to MongoDB and Learn Basic CRUD Operations in 30 minutes

Prabhakar Kumar
9 min readFeb 3, 2021

--

MongoDB

MongoDB is a cross-platform document-oriented database program. It is developed by MongoDB Inc in 2007. It is classified as a NoSQL Database(schema-less). It stores data in a JSON database.

Features

  1. Free to use:- The database free to use
  2. Dynamic Schema:- You can change data without affecting existing data.
  3. Great Scalability:- It is horizontally scalable
  4. Very user-friendly:- Developers and Administrators can use it easily.
  5. Great Speed:- You can use constant speed without any outage.
  6. New Service:- It offers cloud-based new services like MongoDB Atlas.

Documents vs Collections

A document is defined as a record in a MongoDB collection and the basic unit of data in MongoDB. Documents look like JSON objects but they exist as BSON.

{
title: 'Post Two',
body: 'Body of post two',
category: 'Technology',
date: Date()
}

Here’s an example of a Document that stores some data for an article. You can tell it's stored using BSON because there are quotation marks around both the key/value pairs.

Collection

A collection is a grouping of MongoDB documents. Typically, all documents in a collection have a similar or related purpose.

{
title: 'Post Two',
body: 'Body of post two',
category: 'Technology',
date: Date()
},
{
title: 'Post Three',
body: 'Body of post three',
category: 'News',
date: Date()
}

Download & Install MongoDB on Windows

Step 1 — Download the MongoDB MSI Installer Package

Head over here and download the current version of MongoDB. Make sure you select MSI as the package you want to download.

Step 2 — Install MongoDB with the Installation Wizard

A. Make sure you are logged in as a user with Admin privileges. Then navigate to your downloads folder and double click on the .msi package you just downloaded. This will launch the installation wizard.

B. Click Next to start the installation.

C. Accept the license agreement then click Next.

D. Select the Complete setup.

E. Select “Run service as Network Service user” and make a note of the data directory, we’ll need this later.

F. We won’t need Mongo Compass, so deselect it and click Next.

G. Click Install to begin the installation.

F. Hit Finish completing installation.

Step 3 — Create the Data Folders to Store our Databases

A. Navigate to the C Drive on your computer using Explorer and create a new folder called data here.

B. Inside the data folder you just created, create another folder called DB.

Step 4 — Setup Alias Shortcuts for Mongo and Mongod

Once installation is complete, we’ll need to set up MongoDB on the local system.

A. Open up your Hyper terminal running Git Bash.

B. Change directory to your home directory with the following command:

cd ~

C. Here, we’re going to create a file called .bash_profile using the following command:

touch .bash_profile

D. Open the newly created .bash_profile with vim using the following command:

vim .bash_profile

E. In vim, hit the I key on the keyboard to enter insert mode.

F. In your explorer go to C → Program Files → MongoDB → Server

Now you should see the version of your MongoDB.

G. Paste in the following code into vim, make sure you replace the 4.0 with the version that you see in explorer

alias mongod="/c/Program\ files/MongoDB/Server/4.0/bin/mongod.exe"
alias mongo="/c/Program\ Files/MongoDB/Server/4.0/bin/mongo.exe"

F. Hit the Escape key on your keyboard to exit the insert mode. Then type

:wq!

to save and exit Vim.

Step 5 — Verify That Setup was Successful

A. Close down the current Hyper terminal and quit the application.

B. Re-launch Hyper.

C. Type the following commands into the Hyper terminal:

mongo --version

Once you’ve hit enter, you should see something like this:

This means that you have successfully installed and set up MongoDB on your local system!

{
_id: 1,
zipcode: "63109",
subject: [ "English","Hindi"],
students: [
{ name: "john", school: 102, age: 10 },
{ name: "jess", school: 102, age: 11 },
{ name: "jeff", school: 108, age: 15 }
]
},
{
_id: 2,
zipcode: "63110",
subject: [ "Urdu","Computer"],
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
},
{
_id: 3,
zipcode: "63109",
subject: [ "Math","Science"],
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
},
{
_id: 4,
zipcode: "63109",
subject:["Punjabi","Sanskrit"],
students: [
{ name: "barney", school: 102, age: 7 },
{ name: "ruth", school: 102, age: 16 },
]
}

here is the student.json file which is used for practice.

Basic Commands for MongoDB

Start mongo in shell

mongo

show all databases which have you created

show dbs

To create a new database and switch to DB test

use test

To ensure which database you are working

db

Show collections from your current database

show collections 
or
show tables

To create a collection which name is restaurants in your current database

db.createCollection("student")

Insert Methods (Create)

  1. Insert a new document or multiple docume­nts(if provided an array of documents) in the collec­tion. Options: write C­oncern, ordered.
db.collection.insert(document(s) ,[options]) //syntaxdb.student.insert(document(s),[options])
  1. If the collection does not exist, then the insertOne() method creates the collection.insertOne() is not compatible with db.collection.explain().
db.student.insertOne({
_id: 1,
zipcode: "63109",
subject: [ "English","Hindi"],
students: [
{ name: "john", school: 102, age: 10 },
{ name: "jess", school: 102, age: 11 },
{ name: "jeff", school: 108, age: 15 }
]
})
  1. Inserts multiple documents into a collection. insertMany() inserts each document in the array into the collection.
db.student.insertMany([{
_id: 2,
zipcode: "63110",
subject: [ "Urdu","Computer"],
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
},
{
_id: 3,
zipcode: "63109",
subject: [ "Math","Science"],
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
}])

Find Operations(Read)

  1. Displays documents from "­col­lec­tio­n" (first 10) in your current database.
db.collection.find() //syntax

db.student.find()

Type "­it" to see more documents after the prev command.

db.collection.find(<query>).pretty() //synataxdb.student.find(<query>).pretty()

By using find(). pretty () you can get to return data in a format that is easier for humans to parse.

2. Find all documents by condit­ions, with optional fields selection in your current database.

db.collection.find(query, projection) //syntax

db.student.find({},{"zipcode":1,"subject":1,"_id":1});
//To display the fields of zipcode,subject and id.

3. Find n document by conditions in your current database.

db.collection.find(query).limit(numbers) //syntax

4. Find the documents through the Sort key in ascending (1) or descending (-1) order.

db.collection.find().sort(key:1|-1) //syntax

db.student.find().sort({"_id":-1})
//To display all students in ascending order

5. The skip() method controls the starting point of the results set. It is skipping 5 documents (similar to offset).

db.collection.find().skip(number) //syntax

db.student.find({"_id":2}).skip(2);
//To display the students after skipping first 2 which id is 2.

6. $count:- It is used to count how many available results are in the collection.

db.collection.find(query).count() //syntaxdb.student.find({_id:{$gt:1}}).count()
// 3 (it gives 3 results)

Query Selector: Comparison Filters

  1. $in(Array):- The $in operator selects the documents where the value of a field equals any value in the specified array or $nin(Array) is used for Elements with values not contained in Array.
db.collection.find({ field: { $in: [<value1>, <value2>, ... <valueN> ] } })//syntax

db.student.find({subject:{$in:["Punjabi","Hindi"]}})
//To display student details which have choose punjabi and hindi subject.

2. $eq :- Matches values that are equal to a specified value.

db.collection.find({key:{$eq:<value>}}) //synataxdb.student.find({_id:{$eq:4}})
//To display student detils which id is 4.

3. $gt:-Matches values that are greater than a specified value.

4. $gte :- Matches values that are greater than or equal to a specified value.

db.collection.find({key:{$gt/$gte:<value>}}) //syntaxdb.student.find({_id:{$gt:1}})
//To display student details which id is greater than 1

5. $lt:- Matches values that are less than a specified value.

6. $lte:- Matches values that are less than or equal to a specified value.

7. $ne:- Matches all values that are not equal to a specified value.

db.collection.find({key:{$lt/$lte:<value>}}) //syntaxdb.student.find({_id:{$lt:2}})
//To display student details which id is less than 2

9. $and:- Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.

db.collection.find({ $and: [ { <expression1> }, { <expression2> } ] })//syntax

db.student.find({$and:[{"_id":4},{"subject":"Punjabi"}]})
//To display student details which id is 4 and selecting subject Punjabi.

10 $or:- Joins query clauses with a logical OR returns all documents that match the conditions of either clause.

db.collection.find({ $or: [ { <expression1> }, { <expression2> }, ] })//syntax

db.student.find({$or:[{"_id":3},{"subject":"Hindi"}]})
//To display student details which id is 3 or selecting subject Hindi.

10 $regex:- MongoDB uses $regex operator as a regular expression for finding patterns in a string.

db.student.find({"subject":{$regex:/Ur/}})
  1. $elemMatch:- The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
db.student.find({"students":{$elemMatch:{age:{$lt:10}}}})
//To find all the students which age is less than 10.

Query on Embedded/Nested Documents

To specify a query condition on fields in an embedded/nested document, use dot notation ("field.nestedField").

db.collection.find({do­c.s­ubd­oc:­val­ue}) //syntax

//To display student details which age are less than 10.

Update methods

Modifies an existing document or documents in a collection. The method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter.

These are the following methods to update the document

  1. updat­eOn­e(f­ilter, data, options):- Change one document.
  2. updat­eMa­ny(­filter, [data, options]):- Change many documents.
  3. repla­ceO­ne(­filter, data, options):- Replace document entirely
db.student.updateOne({"_id":4},{$set:{"zipcode":"54682"}})

db.student.updateMany({"_id":3},[{$set:{"zipcode":"54682"}},{$set:{"students.school":105}}])

db.student.replaceOne({"_id":3},{"_id":3,processed:"true","Division":"1st"})

Updating the value in Array

$push:- The $push operator appends a specified value to an array.

db.collection.updateOne(filter,{ $push: { <field1>: <value1>, ... } }) //syntax

db.student.updateOne({_id:4},{$push:{"subject":"Urdu"}})

Removing a value in Array

$pull:- The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

db.collection.updateOne(filter,{ $pull: { <field1>: <value1>, ... } }) //syntax

db.student.updateOne({_id:4},{$pull:{"subject":"Urdu"}})

Deleting a field with its data from a document

$unset:- In MongoDB, the $unset operator is used to delete a particular field. The value specified in the $unset expression does not make any impact on the operation. The $unset has no effect when the field does not exist in the document.

db.collection.updateOne(filter,{ $unset: { <field1>: "", ... } }) //syntax

Delete Methods

To delete documents from a collection:-

1.delet­eOn­e(f­ilter, options):- Delete one document

2.delet­eMa­ny(­filter, options) :- Delete many documents

db.student.deleteOne({_id:3}
//delete the document which contains id=3.
db.student.deleteMany({_id:{$lt:3}}
//delete the documents which contains id is less than 3.

To delete all documents from a collection, pass an empty filter document {} to the db.collection.deleteMany() method.

Delete a table from the database

  1. db.collection.drop():- To delete the collection from the database.
db.student.drop() 
//Delete student collection from the current database

Delete the database

MongoDB db.dropDatabase() command is used to drop a existing database.

Click on Articles to see what other views might have in store or add your own ✨

  1. MongoDB Documentation
  2. MongoDB Cheat Sheet

--

--