Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
MongoDB 4 Quick Start Guide

You're reading from  MongoDB 4 Quick Start Guide

Product type Book
Published in Sep 2018
Publisher Packt
ISBN-13 9781789343533
Pages 192 pages
Edition 1st Edition
Languages
Concepts
Author (1):
Doug Bierer Doug Bierer
Profile icon Doug Bierer

Using the MongoDB Shell

This chapter covers how to use the mongo (https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) command shell to perform simple CRUD (Create, Read, Update, and Delete) operations on the database. In addition, you'll learn how to customize the shell and run scripts directly from the command line. This chapter will be of critical interest to DBAs (database admins), but also developers and IT professionals who want to know what is possible.

The topics that we will learn in this chapter are:

  • Overview
  • Performing Simple Queries
  • Database and Collection Operations
  • Creating, Updating, or Deleting Documents
  • Creating and Running Shell Scripts

Overview

The mongo is an executable installed as part of MongoDB. When run, this utility provides an interactive JavaScript command line style interface to the MongoDB database. You can use the shell to perform any and all actions on the MongoDB database including queries, adding, editing, and removing documents from collections. You can also perform higher level operations such as creating a database and collections.

Why use the mongo shell?

A fair question to ask is why use the mongo shell? After all, given that the wonderful graphical utility MongoDB Compass is provided free-of-charge, why bother with the shell? The answer lies in the very nature of Compass; it's graphical in nature, which means you are out of luck...

Performing simple queries

Command summary (discussed as follows):

  • db.<collection>.find({<filter>},{<projection>}).<aggregation>(): Returns only one or more documents based on the filter expression. The projection expression includes or excludes document fields. Aggregation is used to manipulate the final result set (for example, sort(), limit(), and so on).
  • db.<collection>.findOne({<filter>},{<projection>}): Returns only one document based on the filter expression. The projection expression includes or excludes document fields.

One of the most common operations on any database is querying the database for information, which will then form the basis of reports and information that might appear on a web page. In MongoDB the primary command to perform a query is db.<collection>.find(). There is also a variation db.<collection...

Database and collection operations

Occasionally, you may find yourself in the position where you need to do quick edits on the database. As we mentioned, you can often use the GUI tool MongoDB Compass, however there may be times when you are limited an SSH connection and command line access. The best word of advice we can give you at this point is to brush up on your JavaScript! In this sub-section we will cover creating and dropping databases and collections.

Working with databases

Command summary (discussed in the following):

  • Create a Database:
      use <dbName>;
db.<collection>.insertOne({ // document });
  • Drop a Database:
      use <dbName>;
db.dropDatabase();

To create a database in MongoDB...

Creating, updating, or deleting documents

In MongoDB, the document is the lowest atomic unit that can be addressed. As mentioned in Chapter 2, Understanding MongoDB Data Structures, a document is a JSON expression that contains a set of key:value pairs. The key is the name of the field and the value is the actual data used to form the document.

The MongoDB API consistently provides methods for both single and multiple operations. The generic form is (insert|update|delete)(One|Many)(). So, for example, if you wish to insert many documents, use insertMany(). If you only wish to delete only one, use deleteOne(), and so forth.

Creating one or more documents

Command summary (discussed in the following):

  • db.<collection>...

Creating and running shell scripts

Command summary (discussed as follows):

  • mongo [<database>] --eval "command": Direct command execution
  • mongo <JavaScript>: Runs the shell script specified

There are two ways in which you can run a shell script using mongo; issuing a direct (single) command using the --eval flag, or by creating and running a shell script.

Running a direct command

Often, you simply want to get status information on MongoDB, in which case the database is irrelevant. In this example, we use the --eval flag to run the command db.serverStatus():

In other cases, you might want to run periodic database queries from a cron job. Here is an example where we check for customers in the sweetscomplete...

Summary

In this chapter, you learned what the mongo shell is, and why you should use it. You also learned how to access the mongo shell, including several command-line options that allow you to run scripts and single commands. You then learned how to query the database from the command shell, with examples on how to define the filter and projection. After that, you learned how to add, edit, and delete using the command shell. Finally, you learned how to create and run a shell script.

In the next chapter, you'll learn about development using program language drivers.

lock icon The rest of the chapter is locked
You have been reading a chapter from
MongoDB 4 Quick Start Guide
Published in: Sep 2018 Publisher: Packt ISBN-13: 9781789343533
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}