Installing MongoDB 8.2.7 on openEuler
Experiment Report
0 Software Versions
Linux Version: openEuler 24.03 SP2 LTS
Hadoop Version: hadoop3.4.1
HBase Version: hbase2.6.4
MongoDB Version: 8.2.7
MongoDB Compass Version: 1.45.4
Reference Links:
https://www.mongodb.com/try/download/compass
https://forum.openeuler.org/t/topic/6002
x MongoDB Introduction
x.1 Concepts
MongoDB is an open-source database written in C++ and based on distributed file storage, belonging to the NoSQL category.
MongoDB is a product positioned between relational and non-relational databases, and is the most feature-rich NoSQL database that resembles a relational database the most. It is document-oriented, simple and easy to install and operate, and supports various popular programming languages such as Python, Node.js, Java, C++, PHP, and C#. It is widely used in big data, content management, continuous delivery, mobile applications, social applications, user data management, and data centers.
MongoDB is a document database that uses BSON (Binary JSON) format to store and query data. It is a flexible and scalable database solution suitable for various applications. Key features of MongoDB include:
-
Dynamic Schema: MongoDB uses a dynamic schema, allowing data to be stored and processed without predefined data structures. This flexibility makes MongoDB ideal for applications that frequently change their data models.
-
Horizontal Scalability: MongoDB supports horizontal scaling by splitting data across multiple servers using sharding technology. This enhances database performance and availability.
-
High Performance: MongoDB offers high performance with support for indexing and complex queries, enabling fast processing of large volumes of read and write operations.
x.2 Advantages of MongoDB
Advantages of MongoDB over RDBMS:
- No fixed schema structure.
- Data structure consists of key-value (key => value) pairs. MongoDB documents resemble JSON objects. Field values can include nested documents, arrays, and arrays of documents, making the structure of a single object clear.
- No complex table joins. No need to maintain internal relationships between tables.
- Powerful query capabilities. MongoDB’s query functionality is nearly as powerful as SQL, using a document-based query language that enables dynamic querying of documents.
- Easy tuning and scaling. Offers high performance, high availability, and scalability.
- Natural alignment between application objects and database objects.
- Supports both in-memory and disk-based storage, provides rich query operations and indexing support, and includes transaction capabilities (multi-document transactions were truly supported starting from MongoDB 4.0).
x.3 Terminology Comparison
| SQL | MongoDB |
|---|---|
| Database | Database |
| Table | Collection |
| Row / Record | Document |
| Column / Field | Field / Key / Attribute |
| Primary Key | ObjectId |
| Index | Index |
x.4 Basic Operations
| Command | Description |
|---|---|
db.help() |
Help on db methods – View available database operations |
db.mycoll.help() |
Help on collection methods – View available collection operations |
sh.help() |
Sharding helpers – View shard-related help information |
rs.help() |
Replica set helpers – View replica set-related help information |
help admin |
Administrative help – View administrative operation help |
help connect |
Connecting to a DB help – View connection-related help |
help keys |
Key shortcuts – View keyboard shortcuts |
help misc |
Misc things to know – View miscellaneous useful information |
help mr |
MapReduce – View MapReduce-related help |
show dbs |
Show database names – View all databases in the current system |
show collections |
Show collections in current database – View all collections in the current database |
show users |
Show users in current database – View all admin users in the current database |
show profile |
Show most recent system.profile entries with time ≥ 1ms |
show logs |
Show accessible logger names – View all log names |
show log [name] |
Print the last segment of log in memory; ‘global’ is default – View specific log information |
use <db_name> |
Switch to a specified database |
db.mycoll.find()
list objects in collection mycoll list all documents in the currently specified collection
db.mycoll.find({ a : 1 })
list objects in mycoll where a == 1 query all documents in the specified collection based on the condition
it
result of the last line evaluated; use to further iterate view more query results, equivalent to the next page
DBQuery.shellBatchSize = x
set default number of items to display on shell modify the default number of results displayed per page, default is 20
exit
quit the mongo shell exit the terminal
1 Installing MongoDB
Follow these steps to install MongoDB Community Edition (Community Version) on Linux.
1.1 Download the Installation Package
https://www.mongodb.com/try/download/community
# Query system architecture
uname -m
Installing MongoDB 8.2.7 on openEuler
Lab Report
0 Software Versions
\> Linux version: OpenEuler 24.03 SP2 LTS
\> Hadoop version: hadoop3.4.1
\> HBase version: hbase2.6.4
\> MongoDB version: 8.2.7
\> MongoDB Compass version: 1.45.4
\> Reference links:
https://www.mongodb.com/try/download/compass
https://forum.openeuler.org/t/topic/6002
x MongoDB Introduction
x.1 Concepts
MongoDB is an open-source database written in C++ and based on distributed file storage, belonging to the NoSQL category.
MongoDB is a product positioned between relational and non-relational databases, and is the most feature-rich and most SQL-like NoSQL database among non-relational databases. It is document-oriented, simple to install and operate, and supports various popular programming languages such as Python, Node.js, Java, C++, PHP, and C#. It is widely used in big data, content management, continuous delivery, mobile applications, social applications, user data management, data centers, and more.
MongoDB is a document database that uses BSON (Binary JSON) format to store and query data. It is a flexible and scalable database solution suitable for various applications. Key features of MongoDB include:
- Dynamic schema: MongoDB uses a dynamic schema, allowing data to be stored and processed without predefined data structures. This flexibility makes MongoDB ideal for applications that frequently change their data models.
- Horizontal scaling: MongoDB supports horizontal scaling by sharding data across multiple servers. This improves database performance and availability.
- High performance: MongoDB offers high performance, supporting indexes and complex queries, enabling fast handling of large volumes of read and write operations.
x.2 Advantages of MongoDB
Advantages of MongoDB over RDBMS:
- No fixed structure.
- Data structure consists of key-value (key => value) pairs. MongoDB documents resemble JSON objects. Field values can include nested documents, arrays, and arrays of documents, making the structure of a single object clear.
- No complex table joins. There is no need to maintain internal relationships between tables.
- Powerful query capabilities. MongoDB’s query functionality is nearly as powerful as SQL, using a document-based query language that supports dynamic querying of documents.
- Easy tuning and scaling. Offers high performance, high availability, and scalability.
- Natural correspondence between application objects and database objects.
- Supports both in-memory and disk-based storage, provides rich query operations and index support, and includes transaction operations (true multi-document transactions were introduced in MongoDB 4.0).
x.3 Terminology Comparison
| SQL | MongoDB |
|---|---|
| Database | Database |
| Table | Collection |
| Row/Record | Document |
| Column/Field | Field/Key/Attribute |
| Primary Key | ObjectId |
| Index | Index |
x.4 Basic Operations
Command
Description
db.help()
help on db methods view available database methods
db.mycoll.help()
help on collection methods view available collection methods
sh.help()
sharding helpers view help information for sharded clusters
rs.help()
replica set helpers view help information for replica sets
help admin
administrative help view help for administrative operations
help connect
connecting to a db help view help for connecting to a database
help keys
key shortcuts
help misc
miscellaneous useful information
help mr
mapreduce
show dbs
show database names view all databases in the current system
show collections
show collections in current database view all collections in the current database
show users
show users in current database view all administrator users in the current database
show profile
show most recent system.profile entries with time >= 1ms
show logs
show the accessible logger names view all logs
show log [name]
prints out the last segment of log in memory, ‘global’ is default view specified log information
use <db_name>
| |
|----|set current database switch the database for operations
db.mycoll.find()
list objects in collection mycoll list all documents in the currently specified collection
db.mycoll.find({ a : 1 })
list objects in mycoll where a == 1 query all documents in the specified collection based on the condition
it
result of the last line evaluated; use to further iterate view more query results, equivalent to the next page
DBQuery.shellBatchSize = x
set default number of items to display on shell modify the default number of items displayed per page in the result set (default: 20)
exit
quit the mongo shell exit the terminal
1 Installing MongoDB
Follow these steps to install MongoDB Community Edition (Community Version) on Linux.
1.1 Download the Installation Package
https://www.mongodb.com/try/download/community
# Check system architecture
uname -m

If the output is:

Select the tgz format for CentOS 9.3 x64 platform:

1.2 Extract and Rename
cd \~ # Enter the home directory of the hadoop user
cd Downloads # Note: In Chinese interface, this may be “Downloads”
# Extract the file to /usr/local directory, ensure the filename matches the downloaded version
sudo tar -zxvf ./mongodb-linux-x86_64-rhel93-8.2.7 -C /usr/local
The file has been extracted to /usr/local/mongodb-linux-x86_64-rhel93-8.2.7. Now rename the folder to [mongodb]:
cd /usr/local/ # Enter the directory
sudo mv ./mongodb-linux-x86_64-rhel93-8.2.7/ ./mongodb # Rename the folder
sudo chown -R hadoop ./mongodb # Change file permissions

After installation, MongoDB 8.2.7 is located at: /usr/local/mongodb
1.3 Create Data Directory
Create directories to store data and logs:
cd /usr/local/mongodb
mkdir data
ls
cd data
mkdir db
mkdir log
1.4 Create mongodb.conf File
Create the config file:
cd /usr/local/mongodb/
vim mongodb.conf
File content:
# mongod.conf
# For documentation of all options, see:
# 自管理配置文件选项 - 数据库手册 - MongoDB Docs
# Where and how to store data.
storage:
dbPath: /usr/local/mongodb/data/db
# Where to write logging data.
systemLog:
destination: file
logAppend: true
path: /usr/local/mongodb/data/log/mongod.log
# Network interfaces
net:
port: 27017
bindIp: 0.0.0.0
processManagement:
fork: true
# Sharding:
# Enterprise-Only Options:
# auditLog:

1.5 Configure Environment Variables
1. Modify .bashrc file:
cd \~
sudo vim \~/.bashrc
2. Add the following lines at the end:
……
export MONGODB_HOME=/usr/local/mongodb/
export PATH=PATH:{MONGODB_HOME}/bin

3. Make environment variables effective:
source \~/.bashrc
1.6 Start MongoDB
mongod --config /usr/local/mongodb/mongodb.conf

# Check if port 27017 is open:
netstat -lntup|grep 27017

Note: The TCP protocol must be open, not HTTP or HTTPS. It cannot be accessed via a browser.
Use the following command to open port 27017 in the firewall:
sudo firewall-cmd --zone=public --add-port=27017/tcp --permanent
sudo firewall-cmd --reload
Appendix: Linux Firewall Commands
- Start firewall:
systemctl start firewalld
- Stop firewall:
systemctl stop firewalld
- Reload firewall:
firewall-cmd --reload
- Check firewall status:
systemctl status firewalld
2 Connecting to MongoDB Using Navicat
2.1 Connect to MongoDB Using Navicat
Enter the IP address of the machine, port number 27017, and click “Test Connection” in the lower-left corner:


Create new databases, collections, etc., in the above interface.
3 Installing MongoDB Shell
The following operations are performed on Windows.
3.1 Download the Installation Package
Download the latest version from the official website:
https://www.mongodb.com/try/download/shell
Select the zip format for Windows x64 platform:

3.2 Extract and Rename
Extract the zip file and place it in a shallow directory, as shown below:

The directory is: D:\tools\mongosh-2.8.3-win32-x64.
Add the bin directory of this folder to the system environment variable: D:\tools\mongosh-2.8.3-win32-x64\bin

In Windows CMD, type mongosh, and the following information appears:

This indicates it cannot connect to 127.0.0.1, because this machine is Windows, not OpenEuler. You need to specify the IP address of the machine where MongoDB service is installed. Use the command: mongosh[ip]

Mongosh 192.168.118.130:27017 # Actual IP of OpenEuler system
3.3 Database Operations
- View current database: db
- Show list of databases: show dbs
- Switch to specified database: use <database_name>
- Execute query: db.<collection_name>.find()
- Insert document: db.<collection_name>.insertOne({ … })
- Update document: db.<collection_name>.updateOne({ … })
- Delete document: db.<collection_name>.deleteOne({ … })
- Exit MongoDB Shell: quit() or exit
For more details, refer to the official tutorial:
https://www.mongodb.com/zh-cn/products/tools/shell

4 Installing MongoDB Compass
The following steps are performed on Windows.
4.1 Download the Installer
Download the latest version from the official website:
https://www.mongodb.com/try/download/compass

Download the executable file and run it.
4.2 Connect to MongoDB

Enter the actual IP address of the Linux system where MongoDB is installed. The default port is 27017.

4.3 Create Database and Collection
As shown in the figure below, enter the database name mongodb and the collection name Student.

Insert Data

First row of data:
{
“name”: “ZhangSan”,
“score”: {
“English”: 65,
“Math”: 86,
“Computer”: 77
}
}
Second row of data:
+
Exported JSON file:

After selecting a collection (e.g., Student), you can export, modify, or delete data.
4.4 Run MongoDB Shell
As shown in the figure below, click the “Open MongoDB shell” button in the top-right corner of the Compass main interface to enter the command-line tool.


Perform MongoDB commands in this window to complete operations such as creating/deleting tables and CRUD (Create, Read, Update, Delete) of data.
1. Query all student information
db[“Sudent”].find({})
2. Query specific student information
db[“Sudent”].find({“name”:“LiSi”})
3. Query math score of a specific student
db[“Sudent”].find({“name”:“LiSi”}, {“score”:1})
4. Update student’s math score
db[“Sudent”].update({“name”:“LiSi”}, { $set: {“score.Math”: 95 }})
5 Using Python to Operate MongoDB
MongoDB is a popular NoSQL database supporting document-oriented data storage. Python provides many libraries and tools for easy interaction with MongoDB. Below are the basic steps to operate MongoDB using Python, including connecting, inserting, querying, updating, and deleting data.
5.1 Connect to MongoDB
First, install the pymongo library, the official Python driver for MongoDB. Use the following command:
pip install pymongo
After installation, use the following code to connect to MongoDB:
import pymongo
Connect to MongoDB
client = pymongo.MongoClient(“mongodb://localhost:27017/”)
Create database
db = client[“mydb”]
5.2 Insert Data
In MongoDB, data is stored as documents—JSON-like objects composed of key-value pairs. In Python, dictionaries represent documents. Here’s an example of inserting one document into MongoDB:
Insert one document into the collection
collection = db[“customers”]
data = {“name”: “John”, “address”: “Highway 37”}
result = collection.insert_one(data)
print(result.inserted_id)
5.3 Query Data
Use the find() method to query data. The find() method returns a cursor object that can be iterated using a for loop. Here’s an example of querying all documents in the customers collection:
Query all data in the collection
collection = db[“customers”]
for data in collection.find():
print(data)
5.4 Update Data
Use update_one() or update_many() methods to update data. update_one() updates the first document matching the condition, while update_many() updates all matching documents. Here’s an example of updating the document where name is “John”:
Update data with specified condition
collection = db[“customers”]
query = {“name”: “John”}
new_values = {“$set”: {“address”: “Canyon 123”}}
result = collection.update_one(query, new_values)
print(result.modified_count, “documents modified”)
5.5 Delete Data
Use delete_one() or delete_many() methods to delete data. delete_one() deletes the first matching document, while delete_many() deletes all matching documents. Here’s an example of deleting documents where name is “John”:
Delete data with specified condition
collection = db[“customers”]
query = {“name”: “John”}
result = collection.delete_one(query)
print(result.deleted_count, “documents deleted”)
5.6 Complete Python Source Code
import pymongo
Connect to MongoDB
client = pymongo.MongoClient(“mongodb://localhost:27017/”)
Create database
db = client[“mydb”]
Insert one document into the collection
collection = db[“customers”]
data = {“name”: “John”, “address”: “Highway 37”}
result = collection.insert_one(data)
print(result.inserted_id)
Query all data in the collection
collection = db[“customers”]
for data in collection.find():
print(data)
Update data with specified condition
collection = db[“customers”]
query = {“name”: “John”}
new_values = {“$set”: {“address”: “Canyon 123”}}
result = collection.update_one(query, new_values)
print(result.modified_count, “documents modified”)
Delete data with specified condition
collection = db[“customers”]
query = {“name”: “John”}
result = collection.delete_one(query)
print(result.deleted_count, “documents deleted”)

Output on local machine:

Select the tgz format for CentOS 9.3 x64 platform:

1.2 Extract and Rename
cd ~ # Enter the home directory of the hadoop user
cd Downloads # Note: In Chinese interface, this may appear as “Downloads”
Extract the file to /usr/local directory. Ensure the filename matches the downloaded version
sudo tar -zxvf ./mongodb-linux-x86_64-rhel93-8.2.7 -C /usr/local
The file is now extracted to /usr/local/mongodb-linux-x86_64-rhel93-8.2.7. Next, rename the folder to [mongodb]:
cd /usr/local/
sudo mv ./mongodb-linux-x86_64-rhel93-8.2.7/ ./mongodb # Rename folder
sudo chown -R hadoop ./mongodb # Change file permissions

After installation, MongoDB 8.2.7 is located at: /usr/local/mongodb
1.3 Create Data Directory
Create directories for storing data and logs:
cd /usr/local/mongodb
mkdir data
ls
cd data
mkdir db
mkdir log
1.4 Create mongodb.conf File
Create the config file:
cd /usr/local/mongodb/
vim mongodb.conf
File content:
mongod.conf
For documentation of all options, see:
自管理配置文件选项 - 数据库手册 - MongoDB Docs
Where and how to store data.
storage:
dbPath: /usr/local/mongodb/data/db
Where to write logging data.
systemLog:
destination: file
logAppend: true
path: /usr/local/mongodb/data/log/mongod.log
Network interfaces
net:
port: 27017
bindIp: 0.0.0.0
processManagement:
fork: true
Sharding:
Enterprise-Only Options:
auditLog:

1.5 Configure Environment Variables
1. Modify .bashrc file:
cd ~
sudo vim ~/.bashrc
2. Add the following lines at the end:
…
export MONGODB_HOME=/usr/local/mongodb/
export PATH=PATH:{MONGODB_HOME}/bin

3. Make environment variables effective:
source ~/.bashrc
1.6 Start MongoDB
mongod --config /usr/local/mongodb/mongodb.conf

Check if port 27017 is open:
netstat -lntup | grep 27017

Note: TCP protocol must be open—not HTTP or HTTPS. It cannot be accessed via a browser.
Use the following command to open port 27017 in the firewall:
sudo firewall-cmd --zone=public --add-port=27017/tcp --permanent
sudo firewall-cmd --reload
Appendix: Linux Firewall Commands
-
Start firewall:
systemctl start firewalld -
Stop firewall:
systemctl stop firewalld -
Restart firewall:
firewall-cmd --reload -
Check firewall status:
systemctl status firewalld
2 Using Navicat to Connect to MongoDB
2.1 Connect to MongoDB Using Navicat
Enter the IP address of your computer, set port to 27017, and click “Test Connection” in the bottom-left corner:


In the above interface, you can create new databases and collections.
3 Installing MongoDB Shell
The following steps are performed on Windows.
3.1 Download Installer
Download the latest version from the official website:
https://www.mongodb.com/try/download/shell
Select the zip format for Windows x64 platform:

3.2 Extract and Rename
Extract the zip file and place it in a shallow directory, as shown below:

Directory path: D:\tools\mongosh-2.8.3-win32-x64
Add the bin directory to the system environment variable: D:\tools\mongosh-2.8.3-win32-x64\bin

In Windows CMD, enter mongosh, and the following information appears:
Cannot connect to 127.0.0.1 because this machine is Windows, not OpenEuler. Specify the IP address of the computer where MongoDB is installed. Command: mongosh :

Mongosh 192.168.118.130:27017 # Actual IP of OpenEuler
3.3 Database Operations
- View current database: db
- Show list of databases: show dbs
- Switch to a specific database: use <database_name>
- Execute query: db.<collection_name>.find()
- Insert document: db.<collection_name>.insertOne({ … })
- Update document: db.<collection_name>.updateOne({ … })
- Delete document: db.<collection_name>.deleteOne({ … })
- Exit MongoDB Shell: quit() or exit
For more details, see the official tutorial:
https://www.mongodb.com/zh-cn/products/tools/shell

4 Installing MongoDB Compass
Perform the following steps on Windows.
4.1 Download the Installer
Download the latest version from the official website:
https://www.mongodb.com/try/download/compass

Download the executable file and run it.
4.2 Connect to MongoDB

Enter the actual IP address of the Linux system where MongoDB is installed. The default port is 27017.

4.3 Create Database and Collection
As shown in the figure below, enter the database name mongodb and collection name Student.

Insert Data

First row of data:
{
“name”: “ZhangSan”,
“score”: {
“English”: 65,
“Math”: 86,
“Computer”: 77
}
}
Second row of data:
+
Exported JSON file:

After selecting a collection (e.g., Student), you can export, modify, or delete data.
4.4 Run MongoDB Shell
As shown in the figure below, click the “Open MongoDB shell” button in the top-right corner of the Compass interface to access the command-line tool.


Perform MongoDB commands in this window to complete operations such as creating and dropping tables, and performing CRUD (Create, Read, Update, Delete) on data.
-
Query all student information
db[“Sudent”].find({}) -
Query specific student information
db[“Sudent”].find({“name”:“LiSi”}) -
Query math score for a specific student
db[“Sudent”].find({“name”:“LiSi”}, {“score”:1}) -
Update student’s math score
db[“Sudent”].update({“name”:“LiSi”}, { $set: {“score.Math”: 95 }})
5 Using Python to Operate MongoDB
MongoDB is a popular NoSQL database supporting document-oriented data storage. Python offers many libraries and tools to interact easily with MongoDB. Below are the basic steps to use Python to work with MongoDB, including connecting, inserting, querying, updating, and deleting data.
5.1 Connect to MongoDB
First, install the pymongo library, the official Python driver for MongoDB. Use the following command:
pip install pymongo
After installation, use the following code to connect to MongoDB:
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Create a database
db = client["mydb"]
5.2 Insert Data
In MongoDB, data is stored as documents—JSON-like objects with key-value pairs. In Python, use dictionaries to represent documents. Here’s an example of inserting a document:
# Insert one document into a collection
collection = db["customers"]
data = {"name": "John", "address": "Highway 37"}
result = collection.insert_one(data)
print(result.inserted_id)
5.3 Query Data
Use the find() method to query data. It returns a cursor object that can be iterated over. Here’s an example to retrieve all documents from the customers collection:
# Query all data in the collection
collection = db["customers"]
for data in collection.find():
print(data)
5.4 Update Data
Use update_one() or update_many() to update data. update_one() updates the first matching document; update_many() updates all matching documents. Example: update the document where name is “John”:
# Update data with a specific condition
collection = db["customers"]
query = {"name": "John"}
new_values = {"$set": {"address": "Canyon 123"}}
result = collection.update_one(query, new_values)
print(result.modified_count, "documents modified")
5.5 Delete Data
Use delete_one() or delete_many() to delete data. delete_one() removes the first matching document; delete_many() removes all matching documents. Example: delete documents where name is “John”:
# Delete data with a specific condition
collection = db["customers"]
query = {"name": "John"}
result = collection.delete_one(query)
print(result.deleted_count, "documents deleted")
5.6 Complete Python Source Code
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Create database
db = client["mydb"]
# Insert one document
collection = db["customers"]
data = {"name": "John", "address": "Highway 37"}
result = collection.insert_one(data)
print(result.inserted_id)
# Query all data
collection = db["customers"]
for data in collection.find():
print(data)
# Update data
collection = db["customers"]
query = {"name": "John"}
new_values = {"$set": {"address": "Canyon 123"}}
result = collection.update_one(query, new_values)
print(result.modified_count, "documents modified")
# Delete data
collection = db["customers"]
query = {"name": "John"}
result = collection.delete_one(query)
print(result.deleted_count, "documents deleted")
