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.
Join the DZone community and get the full member experience.
Join For FreeThis 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:
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!
Opinions expressed by DZone contributors are their own.
Comments