Free Shipping

Secure Payment

easy returns

24/7 support

  • Home
  • Blog
  • An Introduction to MongoDB and CRUD Manipulations

An Introduction to MongoDB and CRUD Manipulations

 July 8  | 0 Comments

MongoDB Over RDBMS

  • MongoDB is schema-less, where one collection holds different documents (records/rows)
  • No complex Joins are present
  • MongoDB supports a deep query ability, i.e., documents inside collections are queried through the document query language, which is as powerful as SQL
  • MongoDB is easy to scale
  • No mapping is required, everything is done by itself

Why MongoDB?

  1. Information is stored together for fast query access through the MongoDB query language.
  2. MongoDB uses dynamic schemas, meaning, you can create records without first defining the structure, such as the fields or the types of their values.
  3. You can change the structure of records (that we call documents) by simply adding new fields or deleting the existing ones.
  4. This data model gives you the ability to represent hierarchical relationships, to store arrays, and other more complex structures easily.
  5. Documents in a collection need not have an identical set of fields and de-normalization of data is common.
  6. Includes out-of-the-box replication and auto-sharding.

Installation and Testing of the MongoDB Environment in the Windows Platform

Hardware & Software Requirement Specifications for Installing MongoDB on a Windows platform

  • MongoDB runs on most of the Operating Systems, like Linux, Mac, Windows, Solaris, etc., but only on little-endian hardware.
  • Also, 64-bit hardware is usually needed.
  • RAM: Minimum of 2 GB is required.

Refer to the following link with your environments.

https://www.mongodb.com/download-center#community

Follow the Following Steps One at a Time

The following steps are required to install MongoDB on Windows:

Step 1: Download the latest version of MongoDB

Bottom of Form

Make sure you get the correct version of MongoDB depending upon your Windows version. (Choose legacy.)

For 64 bit, use this link to download: https://www.mongodb.org/downloads

Step 2: Extract the zip file.

Step 3: Set up the MongoDB environment.

  • Create a folder with the name MongoDB within this path: C:\mongodb
  • Have a list of four folders along with the one for the property file as shown in the following screenshot.

image1

  • bin folder contains all your Mongo executable files
  • conf file is just the configuration file
  • We use the data folder for the purpose of storing data
  • Create one more folder called db inside it
  • The logs folder is used for checking mongo related errors

Paste the following link in mongodb.conf.txt

# mongodb.conf

# Data

dbpath=c:\mongodb\data\db

# Log

logpath=c:\mongodb\logs\mongodb.log

logappend=true

# Only run on localhost for development

bind_ip=127.0.0.1

# Default MongoDB port

port=27017

Save the file after copy pasting it. With this, we are done with the installation.

Let us test the Mongo environment next.

  • Open the command prompt from C:\mongodb\bin
  • Type mongod.exe

 

Check the following command to ensure successful installation:

  • Open one more command prompt from the same path:

“C:\mongodb\bin”

  • Type: mongo.exe

As we type this command, it shows the following screenshot:

 

When mongo.exe is executed, it is confirming that database is being run on the default port number: 12017

So when we use this for development purposes at the local, mongo binds to the following IP address: 127.0.0.1

With this we are done with MongoDB installation and testing.

CRUD Operations Using MongoDB

Follow the following steps one at a time:

Step 1: Create the database by typing the following commands (refer to the screenshot below):

 

Step 2: Create the collections (i.e., Tables in SQL)

 

Step 3: Insert some records using the following commands:

db.Students.insert(

{ item: “notebook”, qty: 50, tags: [“red”, “hard cover”, “plain”], size: { h: 8.5, w: 11, uom: “in” } }

)

Step 4: Fetch records for the inserted values in the table (Step 3)

  • Type the following commands:

 

db.Students.find().pretty();

Find the following screenshot:

Inserting MongoDB Commands Added in the Mongo Environment

db.collection.insertOne()

Find the syntax below:

db.collection.insertOne(

<document>,

{

writeConcern: <document>

}

)

Syntax explanation:

document: A document (records) that needs to be inserted into the collections

writeConcern: Optional

Find two sample examples with screenshots below:

Sample 1: Insert the document without specifying an _id Field

Type the following code as shown in the screenshot below.

Sample 2: Insert the document specifying an _id field.

 

Observe the IDs in both the samples.

  1. When you insert the document without an ID, MongoDB will automatically assign the objectID which will be unique for all the records,
  2. When you insert the document with an ID, MongoDB will give insertedId as the response.

db.collection.insertMany()

This command signifies multiple documents to the collection.

Find the syntax given below:

db.collection.insertMany(

[ <document 1> , <document 2>, … ],

{

writeConcern: <document>,

ordered: <boolean>

}

)

document: An array of documents to insert into the collections and the datatype is document

writeConcern: Optional, and the datatype ID document

Ordered: It’s optional as well. The datatype is Boolean, specifying the MongoDB instance that should perform an ordered or unordered insert.

We have two samples for the execution.

Sample 1: Insert several documents without specifying an _id field

See the screenshot below for the query and output:

 

Sample 2: Insert the following document with specifying _IDs

 

In both the samples, observe the IDs

Observations:

  1. When you insert the document without an ID, MongoDB will automatically assign an objectID that will be unique for all the records.
  2. When you insert the document with an ID, MongoDB will give an insertedId as the response.

Update Operations in MongoDB

db.collection.update(query, update, options)

Modifies the existing document or documents in the collection and this method can modify the existing document or replace existing documents depending on the update parameter.

By default, the update method is updated in only a single document.

Syntax:

db.collection.update(

<query>,

<update>,

{

Upsert:<boolean>,

multi:<boolean>,

writeConcern:<document>,

Collation: It specifies the protocols such as the usage of letercase and accent marks

collation:<document>

}

Syntax explanation:

query: It’s the selection criteria for the update, and the datatype is document.

<Update>: The modifications to apply, and the datatype is document.

Upsert: This is optional if set to true creates a new document when no document matches with the given criteria and the default value is false which does not insert a document when a new match is found.

multi: It’s also optional if set to true updates multiple documents that meets the query and if set to false updated one document.

writeConcern: Optional

Let’s see the examples on update operation:

Updating the document by ID

Example: Type the following command

db.products.update(

{ _id: 80 },

{

$set: {

item: “Baby Socks”,

}

}

)

See the results in the following screenshots:

To check the updated record in the database, type the following command:

db.products.find().pretty()

Check the following screenshot for the output.

 Deleting Operations in MongoDB

db.collection.remove()

It removes the documents from the collection.

Syntax:

db.collection.remove(

<query>,

<justone>

)

Syntax explanation:

Query specifies deletion criteria using query parameters and the datatype is document. Just one is optional and you can limit the deletion to just one document.

Deletion in MongoDB can be done in two ways:

  • Remove all documents from a collection

db.products.remove({})

See the example shown in the following screenshot:

 

  • Remove a single Document that matches a condition

db.Students.remove({qty:{$gt:50}},true)

 

With this, we’re done with the basic learnings of the MongoDB CRUD installation and its basic concepts.

Conclusion: We hope this blog made you learn the initial basics of the MongoDB environment from installation steps and CRUD manipulations.

Keep visiting www.acadgild.com for more updates on the courses.

 

>