This tutorial will provide a hands-on introduction to the MongoDB Shell (mongo shell), an interactive JavaScript interface to MongoDB. You will learn how to perform basic data operations, queries, and administrative tasks directly from the command line.
By the end of this tutorial, you will:
To begin, launch the MongoDB Shell:
mongo
This command will connect to a MongoDB instance running on localhost and default port 27017.
MongoDB organizes data into databases, and each database contains collections. Collections are similar to tables in relational databases. To see all databases:
show dbs
To switch to or create a database:
use myDatabase
To create a collection:
db.createCollection('myCollection')
CRUD stands for Create, Read, Update, and Delete. These are the four basic functions of persistent storage.
db.myCollection.insert({name: 'John', age: 25, email: 'john@example.com'})
db.myCollection.find()
db.myCollection.update({name: 'John'}, {$set: {email: 'john.doe@example.com'}})
db.myCollection.remove({name: 'John'})
db.myCollection.insertMany([
{name: 'Alice', age: 20, email: 'alice@example.com'},
{name: 'Bob', age: 30, email: 'bob@example.com'}
])
This will insert two new documents into myCollection
.
db.myCollection.find({age: {$gt: 25}})
This will return all documents where age
is greater than 25.
db.myCollection.updateMany({age: {$lt: 25}}, {$set: {status: 'Under 25'}})
This will update all documents where age
is less than 25, setting a new field status
with value 'Under 25'.
In this tutorial, we walked you through a hands-on introduction to the MongoDB Shell. You learned how to connect to a MongoDB instance, create databases and collections, and perform CRUD operations. You also learned how to query with conditions and update multiple documents.
Next, you might want to explore MongoDB's advanced querying capabilities, indexing, and aggregation framework. Start with MongoDB's official documentation, which is an excellent resource.
Create a new database exerciseDB
, and inside this database, create a new collection exerciseCollection
. Insert a document with the following fields: name
, age
, email
.
In exerciseCollection
, find the document you just inserted.
Update the email
field of the document you inserted in Exercise 1.
use exerciseDB
db.createCollection('exerciseCollection')
db.exerciseCollection.insert({name: 'Test', age: 30, email: 'test@example.com'})
db.exerciseCollection.find({name: 'Test'})
db.exerciseCollection.update({name: 'Test'}, {$set: {email: 'test.updated@example.com'}})
Feel free to experiment with different queries and operations to get more comfortable with the MongoDB Shell.