Ubuntu安裝MongoDB最新版的步驟
在安裝前,請確保Ubuntu系統已完成更新(避免依賴沖突),并安裝wget
工具(用于下載文件):
sudo apt update && sudo apt upgrade -y
sudo apt install wget -y
MongoDB使用GPG密鑰驗證軟件包完整性,需先導入其公鑰:
wget -qO - https://www.mongodb.org/static/pgp/server-latest.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-latest.gpg
注:
server-latest.asc
會自動指向MongoDB最新的穩定版本(如8.0),無需手動替換版本號。
根據Ubuntu系統版本(通過lsb_release -cs
獲取代號,如22.04為jammy
、20.04為focal
),添加對應的MongoDB源:
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/latest multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-latest.list
提示:若需指定特定版本(如8.0),可將
latest
替換為版本號(如8.0
)。
更新本地包索引,然后安裝MongoDB Community Edition(默認包含核心服務、Shell工具等):
sudo apt update
sudo apt install -y mongodb-org
安裝完成后,啟動MongoDB服務(進程名mongod
),并設置為開機自動啟動:
sudo systemctl start mongod # 啟動服務
sudo systemctl enable mongod # 開機自啟
通過MongoDB Shell連接數據庫,檢查版本信息確認安裝成功:
mongosh --version # 查看Shell版本
mongosh # 進入Shell
db.version() # 在Shell中執行,顯示MongoDB版本
若能正常進入Shell并顯示版本號(如8.0.0
),則說明安裝完成。
/var/lib/mongodb
,如需更改,編輯/etc/mongod.conf
中的storage.dbPath
字段,然后重啟服務:sudo systemctl restart mongod
/etc/mongod.conf
中的net.bindIp
為0.0.0.0
(允許所有IP連接),然后重啟服務:sudo systemctl restart mongod
admin
數據庫并創建用戶:use admin
db.createUser({ user: "admin", pwd: "your_password", roles: [{ role: "root", db: "admin" }] })
/var/log/mongodb/mongod.log
日志文件,常見原因包括數據目錄權限不足(需將/var/lib/mongodb
所有者設為mongod
:sudo chown -R mongod:mongod /var/lib/mongodb
)或端口被占用(默認27017)。latest
,并運行sudo apt update
更新包列表。