Introduction to MongoDB and Learn Basic CRUD Operations in 30 minutes

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 JSON database.

Features

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 its stored using BSON because there’s 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 installation.

C. Accept the licence 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 installation.

F. Hit Finish to complete 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 your replace the 4.0 with your 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 setup 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 switched 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 crate a collection which name is restaurants in your current databse

db.createCollection("student")

Insert Methods (Create)

db.collection.insert(document(s) [,options]) //syntax
db.collection.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 }
]
})
db.collection.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)

db.collection.find() //syntax

db.student.find()

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

db.collection.find(<query>).pretty() //synatax

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 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 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.rest.find({"_id":2}).skip(2);
//To display the students after skipping first 2 which id is 2.

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

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

Query Selector: Comparison Filters

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/}})
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

db.student.find({"students.age":{$lt:10}})
//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 following methods to update the document

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

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 ✨

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store