Tuto Mongosh
Tuto Mongosh
mongosh is similar to a REPL (Read-Eval-Print Loop), where you can input JavaScript
code, MongoDB commands, and queries, and receive immediate results.
It’s built specifically for MongoDB, allowing you to manage databases, collections,
and documents, perform CRUD operations, and execute more advanced features like
aggregation.
Usefulness of mongosh
To check if mongosh is installed on your system, open your terminal (Command Prompt,
PowerShell, or a terminal on macOS/Linux) and run:
bash
mongosh --version
bash
bash
Basic Syntax:
bash
mongosh "mongodb://<host>:<port>"
<host>: The hostname or IP address where MongoDB is running (e.g., localhost for
local machine).
<port>: The port MongoDB is listening on (default is 27017).
bash
mongosh "mongodb://localhost:27017"
2. Connecting to Remote MongoDB Instance
bash
mongosh "mongodb://<remote_host>:<port>"
Replace <remote_host> with the IP address or hostname of the server and <port> with the
appropriate port number.
bash
mongosh "mongodb://<username>:<password>@localhost:27017"
4. Using MongoDB Atlas (Cloud Service)
bash
mongosh "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test"
bash
mongosh "mongodb://localhost:27017"
If successful, you will be connected to the MongoDB shell, where you can start running
MongoDB commands.
Create a Database
MongoDB creates a database automatically when you insert the first document into a
collection. However, you can "prepare" a database like this:
javascript
// Use the database (creates it if it doesn't exist)
use mydatabase
Create a Collection
javascript
Alternatively, MongoDB will create the collection automatically when you first insert a
document:
javascript
Delete a Collection
To delete a collection:
javascript
db.mycollection.drop()
Delete a Database
javascript
db.dropDatabase()
⚠ Warning: This will permanently delete the database, including all its collections and
documents.
List Databases:
javascript
show dbs
javascript
show collections
CRUD operations
Insert Data:
javascript
-db.stagiaires.insertOne({cne:12345,nom:'karimi farid'})
- db.stagiaires.insertMany([
{
nom_prenom: 'el amrani yassine',
classe: 'RVA 102',
cne: 10003
},
{
nom_prenom: 'benmoussa hanae',
classe: 'RVA 103',
cne: 10004
},
{
nom_prenom: 'boukili hamza',
classe: 'RVA 104',
cne: 10005
}
])
Update Data:
javascript
-db.stagiaires.updateMany({cne:10000},{$set:{nom:'sobhi samia'}})
-db.stagiaires.updateOne({cne:10000},{$set:{nom:'sobhi salim'}})
Delete Data:
javascript
-db.stagiaires.deleteOne({cne:12345})
-db.stagiaires.deleteMany({cne:10000})
Extract Data:
javascript
-db.stagiaires.find()
-db.stagiaires.find({cne:{$gt:10000}})
Example Workflow:
javascript
// Create a collection
db.createCollection("mycollection")
// Insert a document
db.mycollection.insertOne({ name: "Younes", age: 30 })
// List collections
show collections