MongoDB for Beginners: Complete Process from Installation to Querying

MongoDB is a popular document - oriented database. Unlike traditional relational databases such as MySQL, which require pre - defining table structures, MongoDB stores data in a JSON - like format (BSON). Each data item (document) can have different fields, making it very flexible. It is especially suitable for rapid development and storing unstructured or semi - structured data. For beginners, MongoDB has simple and intuitive syntax and a low entry threshold, making it an excellent choice for learning database technology.

1. Installation of MongoDB

1.1 System Verification and Download

MongoDB supports major operating systems such as Windows, macOS, and Linux. Before installation, you need to confirm the system version (for example, Windows 10/11, macOS 12+, Ubuntu 20.04+).
- For Windows users:
Download the corresponding version of the installation package from the MongoDB official website (https://www.mongodb.com/try/download/community). It is recommended to choose the “MSI Installer” (installation program).
When installing, be sure to check “Add MongoDB to PATH” (add environment variables to facilitate subsequent command - line operations). You can keep other options as default. After the installation is complete, the MongoDB service will start automatically.

  • For macOS users:
    It is recommended to install using Homebrew (if not installed, refer to the official website https://brew.sh/ for installation).
    Open the terminal and execute:
  brew tap mongodb/brew
  brew install mongodb - community

After the installation is complete, start the MongoDB service: brew services start mongodb - community.

  • For Linux users (taking Ubuntu as an example):
    Execute the following commands to add the MongoDB source and install:
  wget - qO - https://www.mongodb.org/static/pgp/server - 6.0.asc | sudo apt - key add -
  echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb - org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb - org - 6.0.list
  sudo apt update
  sudo apt install - y mongodb - org

Start the service: sudo systemctl start mongod, and set it to start automatically at boot: sudo systemctl enable mongod.

1.2 Verify Installation

After the installation is complete, open the command line (use cmd/PowerShell for Windows, and terminal for Mac/Linux), and enter mongo (or mongosh, the new version may use mongosh). If you can see the following content, the installation is successful:

> MongoDB shell version v6.0.5
> connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.1
> Implicit session: session { "id" : UUID("...") }
> MongoDB server version: 6.0.5
> >

At this point, you have successfully connected to the local MongoDB service (default port 27017).

2. Basic Concepts of MongoDB

The core concepts of MongoDB are similar to those of relational databases, but the syntax is more concise:
- Database: A container for storing multiple collections, similar to the “database” in MySQL. MongoDB has default databases such as test (test database) and admin (management database), and you can also customize them.
- Collection: A container for storing documents, similar to the “table” in MySQL. Collections do not need pre - defined structures and can dynamically add fields.
- Document: The smallest data unit in MongoDB, stored in a JSON - like format (BSON), containing multiple key - value pairs, similar to the “row” in MySQL. For example:

  {
    "name": "Zhang San",
    "age": 25,
    "hobbies": ["reading", "programming"],
    "address": { "city": "Beijing", "street": "Zhongguancun Street" }
  }

3. Basic Operations (CRUD)

In MongoDB, all operations are performed through the mongo/mongosh client. The following are the core operations:

3.1 Connection and Database Switching

  • The local database is connected to the test database by default. You can use the use command to switch databases (if it does not exist, it will be created, and it will actually exist only after data is inserted):
  > use mydb  # Switch to the mydb database (if it does not exist, an empty database will be created)
  switched to db mydb
  > db  # View the current database
  mydb

3.2 Data Creation and Insertion

MongoDB does not require explicit creation of collections. When inserting data, the collection will be created automatically. Use insertOne() to insert a single piece of data and insertMany() to insert multiple pieces:

  • Insert a single document:
  // Insert a user's information into the "users" collection of the mydb database (the collection name can be customized)
  db.users.insertOne({
    name: "Zhang San",
    age: 25,
    hobbies: ["reading", "running"],
    isStudent: false
  })

The return result after execution is:

  {
    "acknowledged": true,
    "insertedId": ObjectId("650a6f78d1e2f3a4b5c6d7e8")  // The unique ID of the document, generated automatically
  }

3.3 Data Query

Use find() to query the collection and return all documents that meet the conditions; findOne() returns the first matching document.

  • Query all documents:
  db.users.find()  // Return all documents in the users collection

If you need formatted output, you can add .pretty():

  db.users.find().pretty()  // Format the JSON display for better readability
  • Conditional query:
  // Query users over 20 years old
  db.users.find({ age: { $gt: 20 } })  

  // Query users whose name is "Zhang San" (exact match)
  db.users.find({ name: "Zhang San" })  

  // Query users whose name contains "San" (fuzzy match)
  db.users.find({ name: /San/ })  // Regular expression

3.4 Data Update

Use updateOne() to update the first matching document and updateMany() to update all matching documents.

  • Modify fields:
  // Change the age of the user named "Zhang San" to 26
  db.users.updateOne(
    { name: "Zhang San" },  // Condition: name = Zhang San
    { $set: { age: 26 } }  // Update operation: set the age field to 26
  )
  • Note: $set is an update operator in MongoDB, used to modify specified fields; if you directly assign a value (such as {age: 26}), it will overwrite the entire document (use with caution).

3.5 Data Deletion

Use deleteOne() to delete the first matching document and deleteMany() to delete all matching documents.

  • Delete the user named “Zhang San”:
  db.users.deleteOne({ name: "Zhang San" })

4. Common Problems and Precautions

  1. Service not started: If you get a “connection failed” error when executing mongo, check if the MongoDB service is running:
    - For Windows: Task Manager → Services → Is MongoDB running?
    - For Mac/Linux: sudo systemctl status mongod (check status), sudo systemctl start mongod (start the service).

  2. Data types: MongoDB supports types such as strings, numbers, booleans, arrays, and nested objects. For example, hobbies: ["reading", "running"] is an array type.

  3. Remote connection: If you need to connect to a remote MongoDB, you need to start the service and set permissions (in a production environment, configure security groups/passwords). The example is as follows:

   // Connect to a remote server (IP: 192.168.1.100, port 27017)
   mongo --host 192.168.1.100 --port 27017 - u username - p password

5. Summary

As a document - oriented database, MongoDB reduces the entry threshold with its flexible JSON structure and concise syntax. From installation to basic operations (CRUD), the core is to understand the hierarchical relationship of “database → collection → document” and the use of basic methods such as find() and insertOne(). Beginners can first practice locally, and after proficiency, try to operate MongoDB in combination with code (such as Python/Node.js), and gradually learn advanced content such as aggregation queries and index optimization.

Tip: Practice is key. If you encounter problems, you can refer to the official MongoDB documentation (https://www.mongodb.com/docs/) or use the help command to view supported methods.

Xiaoye