MongoDB安裝、基礎(chǔ)操作和聚合實(shí)例介紹
雖然MongoDB這些年很流行,但筆者之前沒(méi)研究過(guò),現(xiàn)在有需求研究這類NoSQL的數(shù)據(jù)庫(kù),是為了驗(yàn)證其是否可被替換。
MongoDB是很輕量的文檔數(shù)據(jù)庫(kù),簡(jiǎn)單測(cè)試也懶得專門(mén)準(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
# 打開(kāi) 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字段值自增長(zhǎng)實(shí)現(xiàn)代碼
這篇文章主要介紹了mongodb字段值自增長(zhǎng)實(shí)現(xiàn),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01MongoDB插入、更新、刪除文檔實(shí)現(xiàn)代碼
本文通過(guò)實(shí)例代碼給大家簡(jiǎn)單介紹了mongodb插入、更新、刪除文檔的方法,需要的的朋友參考下吧2017-04-04Laravel?框架中使用?MongoDB?數(shù)據(jù)庫(kù)的操作
這篇文章主要介紹了Laravel?框架中使用?MongoDB?數(shù)據(jù)庫(kù)的問(wèn)題及操作方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-03-03為MongoDB數(shù)據(jù)庫(kù)注冊(cè)windows服務(wù)
這篇文章介紹了為MongoDB數(shù)據(jù)庫(kù)注冊(cè)windows服務(wù)的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06Centos系統(tǒng)搭建MongoDB數(shù)據(jù)庫(kù)
這篇文章介紹了Centos系統(tǒng)搭建MongoDB數(shù)據(jù)庫(kù)的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04Mongodb啟動(dòng)報(bào)錯(cuò)完美解決方案:about to fork child pr
在使用命令行啟動(dòng) MongoDB 的時(shí)候報(bào)錯(cuò):about to fork child process, waiting until server is ready for connections.forked process: 50411,造成這個(gè)報(bào)錯(cuò)的原因是 “MongoDB” 服務(wù)沒(méi)有正常的關(guān)閉,在終端連接非正常斷開(kāi)后,再次執(zhí)行 MongoDB 的時(shí)候報(bào)錯(cuò)2023-04-04