DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Databases
  4. Mongo Shell, the Key to the MongoDB Kingdom

Mongo Shell, the Key to the MongoDB Kingdom

Take a look at Mongo Shell, a powerful, free tool that can help you perform CRUD operations on MongoDB as well as create indexes to enhance DB performance.

Eugen Hoble user avatar by
Eugen Hoble
·
Oct. 14, 16 · Tutorial
Like (7)
Save
Tweet
Share
6.82K Views

Join the DZone community and get the full member experience.

Join For Free

This article will show how basic CRUD operations can be executed with MongoDB using only Mongo Shell. We'll also show how to create indexes to improve query performance.

Note: The installation of MongoDB will not be explained here.

Why Using Mongo Shell?

The Mongo Shell is an extremely useful tool for developers and database administrators due to the fact that they can run queries against the database, they can optimize queries or administer the database with ease without the need of using any other tool.

Mongo Shell is a free tool included in the MongoDB distribution — a tool that can be customized to meet specific needs. You'll find more details on how to customize it here.

Note: A MongoDB instance must be running before starting a Mongo Shell.

How to Start a MongoDB Instance

To launch a MongoDB instance, just go to the bin folder of your MongoDB installation and type in a console ./mongod.

How to Start Mongo Shell

To launch a Mongo Shell, just go in the bin folder of your MongoDB installation and type ./mongo in a console. This will start a shell that automatically connects to your local MongoDB instance.

Tackling CRUD

Of course, CRUD stands for CREATE, READ, UPDATE, and DELETE — the four operations when working with persisted data no matter whether the data is stored in a relational database (e.g. MySQL) or a NoSQL database (e.g. MongoDB).

A MongoDB sample database is used for the examples in this article, and we'll also be borrowing the zip codes dataset. Some details on how to query the zip codes dataset can also be found here.

Import the Zip Code Dataset

Step #1: Click here and save the data as a JSON file named zipcodes.

Step #2: Use mongoimport to import the downloaded JSON file. Open a console and run the command:

mongoimport--db practice--collection zipcodes --file zipcodes.json


Where $zf contains the path to the JSON datafile. (Here, $zf is a Linux folder alias).

Next, just use show dbs to see the existing databases and use practice to switch to the database that contains zipcodes.

Reading Documents Using Mongo Shell (The R in CRUD)

  • db.collection.find() will list all the documents in the collection.

  • db.collection.findOne() will list only the first document in the collection.

The db.collection.find() method has the following syntax:

db.collection.find(query, projection)

...where the query can contain filters and projection will specify what fields will be returned.

To find all towns with population between 10000 and 20000:

db.zipcodes.find({pop:{$gte:10000,$lte:20000}})

And to count them:

db.zipcodes.find({"pop":{$gte:10000,$lte:20000}}).count()

That gives a result of 3281.

Aside from $gte, which means greater than or equal, and $lte (less than or equal), many other selectors are available (around 35 in all). You can find more details about the available query selectors here.

Inserting Using Mongo Shell (The C in CRUD)

  • db.collection.insert() creates a new document in a collection.

  • db.collection.insertOne() inserts a new document in a collection.

  • db.collection.insertMany() inserts several new documentss in a collection.

The definition of the db.collection.insert() looks like this:

db.collection.insert( [document or array of documents],

{ writeConcern: , ordered:  } ) 

For instance, to insert a new city: 

db.zipcodes.insert({"city":"FALCON CITY",

"loc":[-71.128654,41.070109], "pop":21367, "state":"MA"}) 

Updating Using Mongo Shell (The U in CRUD)

  • db.collection.update() modifies a document in a collection.

  • db.collection.updateOne() modifies a single document in a collection.

  • db.collection.updateMany() modifies multiple documents in a collection.

The definition of the db.collection.update() looks like this:

db.collection.update( [query], [update],

{ upsert: [boolean], multi: [boolean], writeConcern: [document] }) 

Breaking it down:

  • Update represents the modification to be executed.

  • Upsert, if set to true, creates a new document when no document matches the query criteria.

  • Multi, if set to true, updates multiple documents that meet the query criteria. If set to false, it updates one document.

  • WriteConcern represents a document expressing the write concern.

To update an existing document:

db.zipcodes.update( {"city":"FALCON CITY"}, { $set:{"pop":23400} })

Deleting Using Mongo Shell (The D in CRUD)

  • db.collection.remove(): Delete a single document or all documents that match a specified filter.

  • db.collection.deleteOne(): Delete, at most, a single document that matches a specified filter even though multiple documents may match the specified filter.

  • db.collection.deleteMany(): Delete all documents that match a specified filter.

The definition of the db.collection.remove() method looks like this:

db.collection.remove( [query], { justOne: [boolean], writeConcern: [document] } ) 

As in the image above, to remove a city named FALCON CITY, the query used looks like:

db.zipcodes.remove({"city":"FALCON CITY"})

Performance Optimization Using Indexes

Why Use Indexes?

If no indexes are defined for a query, then in order to select only those documents that match the query criteria, MongoDB must scan every document in a collection. If an index has been created for a query, MongoDB can use the index to limit the number of documents it must scan.

To find out more about indexes, please click here.

Create a Single Field Index

db.zipcodes.createIndex({"city":1}) will create an index on the city field — an index in ascending order.

Creating a Compound Index

In the image above, a compound index has been created on the city and state fields.

There are certain rules when working with compound indexes. For instance, if we want the sort operation to use a compound index, we must pay attention to the sort order used for each field when the index has been created.

Very Important!

The way indexes are created and used will have a huge impact on the performance of your application. To verify an index is used, we can examine the query plan using the explain method:

db.zipcodes.find({"state":"MA"}).explain("executionStats")

If we have previously created a simple field index for the state field, the result of a query plan will look like in the image below:

As we can see, when an index exists for the state field, only 474 documents are scanned, and the execution time is 1 millisecond.

But what if we do not have an index created on the state field of a document?

Well, here's the query plan:

As you can see, when there is no index, MongoDB has to scan the whole collection of 29,353 documents to return the 474 for the state="MA". The execution time (if no index exists) exists is 21 milliseconds.

Conclusion

 The Mongo Shell is a powerful, free tool that can be your best friend no matter whether you are a developer or a database administrator. It will allow you to run any CRUD operation, investigate the performance of your queries, and handle other administrative operations — for instance, those related to sharding and replication.

That's all about MongoDB for now. Have fun!

Database MongoDB shell Relational database Document

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Build an Effective CI/CD Pipeline
  • Cucumber.js Tutorial With Examples For Selenium JavaScript
  • Practical Example of Using CSS Layer
  • GitLab vs Jenkins: Which Is the Best CI/CD Tool?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: