Mongo Shell Mongosh 2.1.1 - torarnehave1/slowyouio GitHub Wiki
Comprehensive Guide to Using Mongosh 2.1.1
Introduction
Purpose of the Guide
This guide is designed to provide clear and comprehensive instructions on how to use mongosh
, the MongoDB Shell, for database management tasks. It aims to help both new and experienced users interact effectively with MongoDB.
What is Mongosh?
Mongosh
is the modern command-line interface for MongoDB. It allows for interactive queries, administrative tasks, and a connection point to MongoDB instances. It's a powerful tool that simplifies database management tasks and supports JavaScript syntax, making it highly flexible and useful for developers.
Setting Up Mongosh
Installation
To install mongosh
on different operating systems, follow these steps:
- Windows: Download the latest version from the MongoDB Download Center. Run the installer and follow the on-screen instructions.
- macOS: Use Homebrew:
brew install mongosh
. - Linux: Use the package manager for your distribution, or download it directly from the MongoDB website.
Connecting to MongoDB
- Local Connection: Run
mongosh
to connect to a MongoDB instance running on the default port (27017) on your local machine. - Remote Connection: Use the connection string provided by your MongoDB database host. For example:
Replacemongosh "mongodb+srv://username:password@your-cluster-url/dbname"
username
,password
,your-cluster-url
, anddbname
with your actual details.
Basic Concepts
Terminology
- Database: Contains collections and can have different settings, like authentication.
- Collection: A grouping of MongoDB documents, similar to a table in relational databases.
- Document: A single record in a collection, stored in BSON format.
Navigation
- Switch Databases:
use databaseName
- View Collections:
show collections
CRUD Operations
Creating Data
- Creating Databases and Collections: Automatically create them by inserting data:
use newDatabase db.createCollection("newCollection")
- Inserting Documents:
db.collectionName.insertOne({name: "John", age: 30}) db.collectionName.insertMany([{name: "Jane", age: 25}, {name: "Doe", age: 35}])
Reading Data
- Listing Databases:
show dbs
- Querying Documents:
db.collectionName.find({age: {$gte: 30}})
Updating Data
- Updating Documents:
db.collectionName.updateOne({name: "John"}, {$set: {age: 31}}) db.collectionName.updateMany({}, {$set: {status: "active"}})
Deleting Data
- Deleting Documents:
db.collectionName.deleteOne({name: "John"}) db.collectionName.deleteMany({status: "inactive"})
Advanced Operations
Index Management
- Create an Index:
db.collectionName.createIndex({name: 1})
Aggregation
- Use an Aggregation Pipeline:
db.collectionName.aggregate([{ $match: { status: "active" } }, { $group: { _id: "$age", total: { $sum: 1 } } }])
Transactions
- Handle Transactions:
db.runCommand({ startTransaction: 1 }); db.collectionName.updateOne({name: "John"}, {$set: {age: 32}}); db.runCommand({ commitTransaction: 1 });
Counting and Renaming
Counting Documents
- Count Documents:
db.collectionName.countDocuments({status: "active"})
Renaming Collections
- Rename a Collection:
db.oldCollectionName.renameCollection("newCollectionName")
Additional Features
Scripting in Mongosh
Run scripts by loading JavaScript files directly in mongosh
:
load("script.js")
Customizing the Mongosh Environment
Set preferences like output format and verbosity in .mongoshrc.js
in your home directory.
Troubleshooting
Common Issues and Solutions
Problems like connection errors or syntax issues are common; checking MongoDB's official documentation often provides quick solutions.
Conclusion
This guide covered essential mongosh
functionalities to help you manage MongoDB databases efficiently. For deeper understanding, visit MongoDB's documentation.
Appendix
Command Reference Sheet
Quick reference for all mongosh
commands covered
in the guide for easy access.
Here's a basic guide to using mongosh
version 2.1.1, categorized by common CRUD operations for databases, collections, and documents. This guide also includes instructions on counting documents, renaming collections, and adding fields to documents in a collection.
1. Connecting to a MongoDB Instance
First, you'll need to open your terminal and connect to your MongoDB instance using mongosh
. If you're connecting to a local MongoDB server, you can simply type:
mongosh
To connect to a remote MongoDB instance, use:
mongosh "mongodb+srv://your-username:your-password@your-cluster-url/myDatabase"
Replace your-username
, your-password
, your-cluster-url
, and myDatabase
with your actual MongoDB credentials and database name.
2. CRUD Operations
Creating (C)
-
Databases: Switch to a non-existing database to create one:
use newDatabaseName
This creates
newDatabaseName
if it doesn't exist. -
Collections: Create a new collection:
db.createCollection("newCollectionName")
-
Documents: Insert a document into a collection:
db.collectionName.insertOne({name: "John", age: 30})
Reading (R)
-
List Databases:
show dbs
-
List Collections:
show collections
-
Find Documents: Retrieve all documents within a collection:
db.collectionName.find({})
Updating (U)
-
Add Fields to Documents: Update a document to add a new field:
db.collectionName.updateMany({}, {$set: {newField: "value"}})
This adds
newField
with the value"value"
to all documents. -
Modify Documents: Modify an existing document:
db.collectionName.updateOne({name: "John"}, {$set: {age: 31}})
Deleting (D)
-
Delete Documents: Remove a single document:
db.collectionName.deleteOne({name: "John"})
-
Delete All Documents:
db.collectionName.deleteMany({})
3. Additional Useful Operations
Counting Documents
-
Count All Documents in a Collection:
db.collectionName.countDocuments()
-
Count with Conditions:
db.collectionName.countDocuments({age: {$gt: 20}})
Renaming Collections
- Rename a Collection:
db.collectionName.renameCollection("newCollectionName")
Adding Fields to a Collection
- Add New Fields to All Documents:
As shown above, use the
$set
operator in anupdateMany
command to add new fields to all documents:db.collectionName.updateMany({}, {$set: {newFieldName: "defaultValue"}})
mongosh
4. Exiting To exit mongosh
, you can simply type:
exit
This guide covers the basic commands needed for managing databases, collections, and documents within mongosh
, along with some additional operations that are commonly used. Be sure to replace placeholder values like collectionName
and newDatabaseName
with your actual database and collection names.