Experiment: MongoDB 8.2.9 Installation and Configuration Guide

Installing MongoDB 8.2.7 on openEuler

Lab Report

0 Software Versions

Linux Version: openEuler 24.03 SP3 LTS
Hadoop Version: hadoop3.5.0
HBase Version: hbase2.5.14
MongoDB Version: 8.2.9
MongoDB Compass Version: 1.49.7
Reference Links:

https://www.mongodb.com/zh-cn/docs/manual/tutorial/install-mongodb-on-ubuntu/#std-label-install-mdb-community-ubuntu

https://www.mongodb.com/try/download/compass

https://forum.openeuler.org/t/topic/6002

x Introduction to MongoDB

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 relational-like NoSQL database among non-relational databases. It is document-oriented, 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 stores and queries data using the BSON (Binary JSON) format. 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 requiring frequent changes to data models.

  • Horizontal Scalability: MongoDB supports horizontal scaling through sharding, which splits and distributes data across multiple servers. This enhances database performance and availability.

  • High Performance: MongoDB offers high performance with support for indexing and complex queries, enabling fast handling of large volumes of read and write operations.

x.2 Advantages of MongoDB

Advantages of MongoDB over RDBMS:

  1. No fixed schema
  2. Data structure based on 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 and intuitive.
  3. No complex table joins. There’s no need to maintain internal relationships between tables.
  4. 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.
  5. Easy tuning and scaling. Offers high performance, high availability, and scalability.
  6. Natural alignment between application objects and database objects.
  7. Supports both in-memory and disk-based storage, provides rich query and indexing 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 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 management 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 – General tips and 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 available logs
show log [name] Prints out 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 specified collection

db.mycoll.find({ a : 1 })

list objects in mycoll where a == 1 query all documents in the specified collection based on a 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

# Check system architecture

uname -m

![|649x160](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps2.jpg)

If the output is:

![|497x86](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps3.jpg)

Select the tgz format for CentOS 9.3 x64:

![|648x438](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps4.jpg)

1.2 Extract and Rename

cd \~ # Enter the home directory of the hadoop user

cd Downloads # Note: In a Chinese interface, this may appear as “Downloads”

# Extract the file to /usr/local, ensuring the filename matches the downloaded version

sudo tar -zxvf ./mongodb-linux-x86_64-rhel93-8.2.9 -C /usr/local

The file has been extracted to /usr/local/mongodb-linux-x86_64-rhel93-8.2.9. Next, rename the folder to [mongodb]

cd /usr/local/ # Enter the directory

sudo mv ./mongodb-linux-x86_64-rhel93-8.2.9/ ./mongodb # Rename the folder

sudo chown -R hadoop ./mongodb # Change file permissions

![|649x118](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps5.jpg)

After installation, MongoDB 8.2.9 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:

  ![|380x388](file:///C:\\Users\\LINHAO\\AppData\\Local\\Temp\\ksohtml25376\\wps6.jpg)

1.5 Configure Environment Variables

1. Modify the .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

![|649x576](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps7.jpg)

3. Make environment variables effective:

source \~/.bashrc

1.6 Start MongoDB

mongod --config /usr/local/mongodb/mongodb.conf

![|648x82](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps8.jpg)

# Check if port 27017 is open:

netstat -lntup|grep 27017

![|649x30](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps9.jpg)

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

  1. Start the firewall:

systemctl start firewalld

  1. Stop the firewall:

systemctl stop firewalld

  1. Restart the firewall:

firewall-cmd --reload

  1. 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 computer and port 27017, then click “Test Connection” in the lower-left corner:

![|370x490](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps10.jpg)

![|649x211](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps11.jpg)

Create new databases and collections 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:

![|648x348](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps12.jpg)

3.2 Extract and Rename

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

![|649x275](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps13.jpg)

Directory: D:\\mongosh

Add the bin directory within this folder to the system environment variables: D:\\mongosh

![|648x404](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps14.jpg)

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

![|650x74](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps15.jpg)

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

![|649x273](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps16.jpg)

Mongosh 192.168.80.128:27017 # Actual IP of OpenEuler

3.3 Database Operations

  • View current database: db
  • Show list of databases: show dbs
  • Switch to specified database: use <database_name>
  • Perform query operation: 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

![|648x348](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps17.jpg)

4 Installing MongoDB Compass

The following steps are performed on Windows.

4.1 Download Installation Package

Download the latest version from the official website:
https://www.mongodb.com/try/download/compass

![|648x348](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps18.jpg)

Download the executable file and run it.

4.2 Connect to MongoDB

![|650x378](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps19.jpg)

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

![|650x364](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps20.jpg)

4.3 Create Database and Collection (Collection)

As shown in the figure below, enter the database name “mongodb” and the collection name “Student”.

![|648x413](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps21.jpg)

Insert Data

![|649x585](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps22.jpg)

First row of data:

{
“name”: “ZhangSan”,
“score”: {
“English”: 65,
“Math”: 86,
“Computer”: 77
}
}

Second row of data:

![|650x545](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps23.jpg)

{
“name”: “LiSi”,
“score”: {
“English”: 55,
“Math”: 100,
“Computer”: 88
}
}

![|649x348](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps24.jpg)

Exported JSON file:

![|466x488](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps25.jpg)

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.

![|501x596](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps26.jpg)

Perform MongoDB commands in this window to complete operations such as creating and deleting tables, and performing CRUD (Create, Read, Update, Delete) on 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 }})

![|650x487](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps27.jpg)

5 Using Python to Operate MongoDB

MongoDB is a popular NoSQL database that supports document-oriented data storage. Python provides many libraries and tools to easily interact with MongoDB. Below are the basic steps to use Python to operate MongoDB, including connecting, inserting, querying, updating, and deleting data.

5.1 Connect to MongoDB

First, install the pymongo library, the official Python library for interacting with MongoDB. Use the following command to install:

pip install pymongo

![|649x202](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps28.jpg)

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”]

![|649x121](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps29.jpg)

5.2 Insert Data

In MongoDB, data is stored in the form of documents. A document is a JSON object composed of key-value pairs. In Python, dictionaries can be used to represent documents. Here is an example of inserting a 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

You can use the find() method to query data. The find() method returns a cursor object, which can be iterated using a for loop. Here is an example of querying all documents in the customers collection in MongoDB:

Query all data in the collection

collection = db[“customers”]
for data in collection.find():
print(data)

5.4 Update Data

Use the update_one() or update_many() method to update data. update_one() updates the first document that matches the condition, while update_many() updates all documents that match the condition. Here is an example of updating the document in the customers collection where the name field is “John”:

Update data matching 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 the delete_one() or delete_many() method to delete data. delete_one() deletes the first document that matches the condition, while delete_many() deletes all documents that match the condition. Here is an example of deleting the document in the customers collection where the name field is “John”:

Delete data matching 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 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 matching 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”)

Delete data matching a specific condition

collection = db[“customers”]
query = {“name”: “John”}
result = collection.delete_one(query)
print(result.deleted_count, “documents deleted”)

![|650x124](file:///C:\Users\LINHAO\AppData\Local\Temp\ksohtml25376\wps30.jpg)