MongoDB Shell Introduction: Simple Database Operations via Command Line

MongoDB Shell is an interactive tool that allows you to directly “communicate” with MongoDB databases via the command line. It is based on JavaScript syntax, making it easy to learn and particularly suitable for beginners to familiarize themselves with basic database operations.

1. What is MongoDB Shell?

MongoDB Shell (abbreviated as mongo) is an official command-line environment provided by MongoDB. Here, you can perform operations such as creating, querying, updating, and deleting data. It enables efficient database management without needing a graphical interface, making it ideal for Linux/Windows/Mac systems.

2. Installing and Starting MongoDB Shell

  1. Install MongoDB: First, ensure MongoDB is installed (download installation packages from the official website). The Shell will be installed with MongoDB upon completion.
  2. Start the Shell: Open the terminal/command prompt and enter mongo to access the Shell environment.
    - After successful startup, you will see a prompt like:
     MongoDB shell version v6.0.0
     connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000
     Implicit session: session { "id" : UUID("...") }
     MongoDB server version: 6.0.0
     > 
  • The > symbol is the Shell’s command prompt, where you can start entering commands.

3. Basic Operations: Connecting and Switching Databases

MongoDB operations are based on the “current database,” which can be switched using the use command.
- View Current Database: Enter db to display the currently active database (default is test).

  > db
  test
  • Switch Databases: Use use <database_name> to switch. For example, switch to myDB (automatically created if it doesn’t exist):
  > use myDB
  switched to db myDB
  > db
  myDB
  • Connect to a Remote Database: For databases on a remote server, use mongo --host <remote_IP> --port <port_number> (default port is 27017).

4. Creating Data: Inserting Documents into Collections

In MongoDB, a document (similar to JSON) is the smallest data unit, and a collection (similar to a relational database “table”) is a container for documents.
- Automatic Collection Creation: Collections are created automatically when data is inserted. For example, insert a document into the students collection:

  > db.students.insertOne({name: "小明", age: 18, major: "计算机"})
  {
    "acknowledged" : true,
    "insertedId" : ObjectId("650a1b2c3d4e5f6a7b8c9d0e"),
    "insertedCount" : 1
  }
  • insertOne(): Inserts a single document; insertMany(): Inserts multiple documents (e.g., db.students.insertMany([{...}, {...}])).
  • MongoDB automatically generates a unique _id (e.g., ObjectId("...")) for each document, so you don’t need to set it manually.

5. Reading Data: Querying Documents

Use the find() method to query collection data, and pretty() to format output for readability.
- Query All Documents: db.<collection_name>.find().pretty()

  > db.students.find().pretty()
  {
    "_id" : ObjectId("650a1b2c3d4e5f6a7b8c9d0e"),
    "name" : "小明",
    "age" : 18,
    "major" : "计算机"
  }
  • Conditional Query: Add a filter to find(), e.g., query students aged 18:
  > db.students.find({age: 18}).pretty()
  {
    "_id" : ObjectId("650a1b2c3d4e5f6a7b8c9d0e"),
    "name" : "小明",
    "age" : 18,
    "major" : "计算机"
  }
  • Single Document Query: Use findOne() to get the first matching result:
  > db.students.findOne({name: "小明"})
  {
    "_id" : ObjectId("650a1b2c3d4e5f6a7b8c9d0e"),
    "name" : "小明",
    "age" : 18,
    "major" : "计算机"
  }

6. Updating Data: Modifying Documents

Use updateOne() (update one) or updateMany() (update multiple) with operators like $set.
- Update a Single Document: Change Xiaoming’s age to 20:

  > db.students.updateOne(
      {name: "小明"},  // Match condition
      {$set: {age: 20}}  // Update operation
    )
  {
    "acknowledged" : true,
    "matchedCount" : 1,
    "modifiedCount" : 1
  }
  • Result Explanation: matchedCount=1 means 1 matching document was found, and modifiedCount=1 means the update was successful.
  • Update Multiple Documents: Increment the age of all students over 18 by 1:
  > db.students.updateMany(
      {age: {$gt: 18}},  // Condition: age > 18
      {$inc: {age: 1}}   // $inc: Increment by 1
    )

7. Deleting Data: Removing Documents

Use deleteOne() (delete one) or deleteMany() (delete multiple).
- Delete a Single Document: Remove the student aged 20:

  > db.students.deleteOne({age: 20})
  {
    "acknowledged" : true,
    "deletedCount" : 1
  }
  • Delete All Data: Clear the students collection (use with caution!):
  > db.students.deleteMany({})
  {
    "acknowledged" : true,
    "deletedCount" : 5  // Assuming 5 documents exist
  }

8. Managing Databases and Collections

  • View All Databases: show dbs (only non-empty databases are displayed).
  • Delete Current Database: Switch to the target database first, then run db.dropDatabase():
  > use myDB
  switched to db myDB
  > db.dropDatabase()
  { "dropped" : "myDB", "ok" : 1 }
  • Delete a Collection: db.<collection_name>.drop(), e.g., delete the students collection:
  > db.students.drop()
  true  // Returns true if deletion is successful

9. Advanced Tips

  1. Count Documents: db.<collection_name>.countDocuments()
   > db.books.countDocuments({author: "小明"})  // Count books by author "小明"
  1. Limit Query Results: Use limit(N) to return only the first N results:
   > db.books.find().limit(3).pretty()  // Return only the first 3 books

10. Learning Suggestions

  • Practice Hands-On: Follow examples to insert, query, and update data.
  • Consult Official Documentation: MongoDB Shell supports full JavaScript syntax; refer to the official manual for complex operations.
  • Start Simple, Move to Complex: Master CRUD basics first, then explore advanced topics like aggregation pipelines and indexes.

The charm of MongoDB Shell lies in its “zero-configuration” approach—no need to pre-create databases/tables; data insertion takes effect immediately. Use the command line to quickly test and iterate, making it the most direct way to get started with MongoDB. Now, open your terminal and start “playing” with databases via code!

Xiaoye