MongoDB安裝、基礎(chǔ)操作和聚合實(shí)例介紹
雖然MongoDB這些年很流行,但筆者之前沒(méi)研究過(guò),現(xiàn)在有需求研究這類NoSQL的數(shù)據(jù)庫(kù),是為了驗(yàn)證其是否可被替換。
MongoDB是很輕量的文檔數(shù)據(jù)庫(kù),簡(jiǎn)單測(cè)試也懶得專門準(zhǔn)備虛擬機(jī)環(huán)境了,直接在macOS上安裝測(cè)試下其基礎(chǔ)功能。
- 1.使用 Homebrew 安裝 MongoDB
- 2.啟動(dòng)/停止 MongoDB 服務(wù)
- 3.啟動(dòng) MongoDB Shell
- 4.體驗(yàn) MongoDB 基本操作
- 5.體驗(yàn) MongoDB 聚合操作
1. 使用 Homebrew 安裝 MongoDB
# 添加 MongoDB 存儲(chǔ)庫(kù) brew tap mongodb/brew # 安裝 MongoDB 社區(qū)版 brew install mongodb-community
2. 啟動(dòng)/停止 MongoDB 服務(wù)
# 啟動(dòng) MongoDB 服務(wù) brew services start mongodb/brew/mongodb-community # 停止 MongoDB 服務(wù)(這個(gè)當(dāng)然要等我們體驗(yàn)測(cè)試完成后才停..) brew services stop mongodb/brew/mongodb-community
3. 啟動(dòng) MongoDB Shell
# 打開 MongoDB 的交互式 Shell mongosh
在mongosh登錄到MongoDB時(shí)可以看到,筆者這里安裝的是7.0.12版本的MongoDB,使用默認(rèn)端口27017:
jingyuzhao@jingyuzhao-mac ~ % mongosh Current Mongosh Log ID: 668ce3d3012a1d349d3a46b3 Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.10 Using MongoDB: 7.0.12 Using Mongosh: 2.2.10 For mongosh info see: https://docs.mongodb.com/mongodb-shell/ ------ The server generated these startup warnings when booting 2024-07-09T15:09:54.021+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted ------ test>
4. 體驗(yàn)MongoDB基本操作
下面進(jìn)行一些基本的 MongoDB 操作示例:
1)創(chuàng)建數(shù)據(jù)庫(kù)和集合:
-- 切換到要使用的數(shù)據(jù)庫(kù)(如果不存在則會(huì)自動(dòng)創(chuàng)建)
use mydb
-- 創(chuàng)建集合
db.createCollection("myCollection")2)插入文檔:
-- 插入單個(gè)文檔:
db.myCollection.insertOne({ name: "Alfred", age: 34 })
-- 插入多個(gè)文檔:
db.myCollection.insertMany([
{ name: "Mcdull", age: 33 },
{ name: "Sally", age: 4 }
])3)查詢文檔:
-- 查詢所有文檔:
db.myCollection.find()
-- 查詢滿足條件的文檔:
db.myCollection.find({ age: { $gt: 25 } })4)更新文檔:
-- 更新單個(gè)文檔:
db.myCollection.updateOne({ name: "Alfred" }, { $set: { age: 29 } })
-- 更新多個(gè)文檔:
db.myCollection.updateMany({ age: { $lt: 35 } }, { $set: { status: "Active" } })5)刪除文檔:
-- 刪除單個(gè)文檔,name值為'Sally'的記錄:
db.myCollection.deleteOne({ name: "Sally" })
-- 刪除多個(gè)文檔,status值為'Active'的記錄:
db.myCollection.deleteMany({ status: "Active" })5. 體驗(yàn)MongoDB聚合操作
1)創(chuàng)建測(cè)試用例
-- 刪除 sales 集合
db.sales.drop()
-- 創(chuàng)建 sales 集合并插入示例文檔
db.sales.insertMany([
{
"order_id": 1001,
"product": "Laptop",
"quantity": 2,
"unit_price": 1200,
"customer": "Alice",
"order_date": ISODate("2024-06-07T08:30:00Z")
},
{
"order_id": 1002,
"product": "Monitor",
"quantity": 1,
"unit_price": 500,
"customer": "Bob",
"order_date": ISODate("2024-06-10T10:15:00Z")
},
{
"order_id": 1003,
"product": "Keyboard",
"quantity": 3,
"unit_price": 50,
"customer": "Alice",
"order_date": ISODate("2024-06-15T14:45:00Z")
},
{
"order_id": 1004,
"product": "Mouse",
"quantity": 5,
"unit_price": 20,
"customer": "Charlie",
"order_date": ISODate("2024-07-09T09:30:00Z")
}
])查詢這個(gè)集合結(jié)果:
db.sales.find()
mydb> db.sales.find()
[
{
_id: ObjectId('668cf766749a72317b175646'),
order_id: 1001,
product: 'Laptop',
quantity: 2,
unit_price: 1200,
customer: 'Alice',
order_date: ISODate('2024-06-07T08:30:00.000Z')
},
{
_id: ObjectId('668cf766749a72317b175647'),
order_id: 1002,
product: 'Monitor',
quantity: 1,
unit_price: 500,
customer: 'Bob',
order_date: ISODate('2024-06-10T10:15:00.000Z')
},
{
_id: ObjectId('668cf766749a72317b175648'),
order_id: 1003,
product: 'Keyboard',
quantity: 3,
unit_price: 50,
customer: 'Alice',
order_date: ISODate('2024-06-15T14:45:00.000Z')
},
{
_id: ObjectId('668cf766749a72317b175649'),
order_id: 1004,
product: 'Mouse',
quantity: 5,
unit_price: 20,
customer: 'Charlie',
order_date: ISODate('2024-07-09T09:30:00.000Z')
}
]
mydb> 2)執(zhí)行聚合操作
示例 1: 計(jì)算每個(gè)客戶的總銷售額和訂單數(shù)量
db.sales.aggregate([
{
$group: {
_id: "$customer",
totalSales: { $sum: { $multiply: ["$quantity", "$unit_price"] } },
totalOrders: { $sum: 1 }
}
},
{ $sort: { totalSales: -1 } } // 按總銷售額降序排序
])查詢結(jié)果:【計(jì)算每個(gè)客戶的總銷售額和訂單數(shù)量】
[
{ _id: 'Alice', totalSales: 2550, totalOrders: 2 },
{ _id: 'Bob', totalSales: 500, totalOrders: 1 },
{ _id: 'Charlie', totalSales: 100, totalOrders: 1 }
]示例 2: 查找每種產(chǎn)品的平均銷售價(jià)格和銷售數(shù)量
db.sales.aggregate([
{
$group: {
_id: "$product",
avgPrice: { $avg: "$unit_price" },
totalQuantity: { $sum: "$quantity" }
}
},
{ $sort: { _id: 1 } } // 按產(chǎn)品名稱升序排序
])查詢結(jié)果:【查找每種產(chǎn)品的平均銷售價(jià)格和銷售數(shù)量】
[
{ _id: 'Keyboard', avgPrice: 50, totalQuantity: 3 },
{ _id: 'Laptop', avgPrice: 1200, totalQuantity: 2 },
{ _id: 'Monitor', avgPrice: 500, totalQuantity: 1 },
{ _id: 'Mouse', avgPrice: 20, totalQuantity: 5 }
]示例 3: 篩選特定日期范圍內(nèi)的銷售訂單并投影字段
db.sales.aggregate([
{
$match: {
order_date: {
$gte: ISODate("2024-06-01"),
$lte: ISODate("2024-06-30")
}
}
},
{
$project: {
order_id: 1,
product: 1,
quantity: 1,
totalAmount: { $multiply: ["$quantity", "$unit_price"] }
}
}
])查詢結(jié)果:【篩選特定日期范圍內(nèi)的銷售訂單并投影字段】
[
{
_id: ObjectId('668cf766749a72317b175646'),
order_id: 1001,
product: 'Laptop',
quantity: 2,
totalAmount: 2400
},
{
_id: ObjectId('668cf766749a72317b175647'),
order_id: 1002,
product: 'Monitor',
quantity: 1,
totalAmount: 500
},
{
_id: ObjectId('668cf766749a72317b175648'),
order_id: 1003,
product: 'Keyboard',
quantity: 3,
totalAmount: 150
}
]至此,我們學(xué)習(xí)了如何安裝、啟動(dòng)和停止 MongoDB,并通過(guò) MongoDB Shell 執(zhí)行基礎(chǔ)的 CRUD 操作(創(chuàng)建、查詢、更新和刪除文檔),同時(shí)探索了 MongoDB 的聚合操作,用于實(shí)現(xiàn)復(fù)雜的數(shù)據(jù)分析。后續(xù),會(huì)繼續(xù)研究關(guān)于Oracle 23ai在JSON這方面的能力表現(xiàn)。
到此這篇關(guān)于MongoDB安裝、基礎(chǔ)操作和聚合實(shí)例詳解的文章就介紹到這了,更多相關(guān)MongoDB安裝內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MongoDB入門教程之細(xì)說(shuō)MongoDB數(shù)據(jù)庫(kù)的增刪查改操作
這篇文章主要介紹了MongoDB入門教程之細(xì)說(shuō)MongoDB數(shù)據(jù)庫(kù)的增刪查改操作,本文環(huán)境是windows,所以以圖片形式講解,需要的朋友可以參考下2014-08-08
MongoDB 正則表達(dá)式查詢之如何在 MongoDB 中實(shí)現(xiàn)模糊搜索與索引優(yōu)化陷阱
本文詳細(xì)介紹了MongoDB正則表達(dá)式的基礎(chǔ)、索引行為、性能優(yōu)化、安全風(fēng)險(xiǎn)、替代方案以及最佳實(shí)踐,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2026-02-02
詳解MongoDB中用sharding將副本集分配至服務(wù)器集群的方法
副本集是MongoDB的主從復(fù)制中的重要功能,經(jīng)常被用來(lái)作額外的備份,這里我們就來(lái)詳解MongoDB中用sharding將副本集分配至服務(wù)器集群的方法,首先還是來(lái)回顧一下MongoDB中副本集的基本知識(shí):2016-07-07
MongoDB數(shù)據(jù)庫(kù)安裝部署及警告優(yōu)化
大家好,本篇文章主要講的是MongoDB數(shù)據(jù)庫(kù)安裝部署及警告優(yōu)化,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽2021-12-12
MongoDB中sort()排序方法、aggregate()聚合方法和索引代碼示例
這篇文章主要給大家介紹了關(guān)于MongoDB中sort()排序方法、aggregate()聚合方法和索引的相關(guān)資料,MongoDB的聚合函數(shù)Aggregate是一組用于對(duì)MongoDB中的數(shù)據(jù)集進(jìn)行聚合操作的函數(shù),文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-04-04
windows安裝mongodb6.x并設(shè)置用戶名密碼的詳細(xì)過(guò)程
這篇文章主要介紹了windows安裝mongodb6.x并設(shè)置用戶名密碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04
MongoDB排序時(shí)內(nèi)存大小限制與創(chuàng)建索引的注意事項(xiàng)詳解
在數(shù)據(jù)量超大的情形下,任何數(shù)據(jù)庫(kù)系統(tǒng)在創(chuàng)建索引時(shí)都是一個(gè)耗時(shí)的大工程,下面這篇文章主要給大家介紹了關(guān)于MongoDB排序時(shí)內(nèi)存大小限制與創(chuàng)建索引的注意事項(xiàng)的相關(guān)資料,需要的朋友可以參考下2022-05-05

