# mongoDB 以下為下載mongoDB的網址: https://www.mongodb.com/try/download/community ![](https://hackmd.io/_uploads/SkfPGdD83.png) ![](https://hackmd.io/_uploads/SJYOf_DLh.png) ## 安裝指令 echo logpath=D:\mongodb\log\mongo.log>D:\mongodb\mongod.cfg echo dbpath=D:\mongodb\data\db >> D:\mongodb\mongod.cfg D:\mongodb\bin\mongod.exe --config D:\mongodb\mongod.cfg --install net start MongoDB ## 下載S3 以下為下載Robo3T的網址: https://robomongo.org/ ![](https://hackmd.io/_uploads/r1sBVuDU2.png) ## 第二天練習 mongoDB **滑鼠按右鍵 點選Open IntelliShell** ![](https://hackmd.io/_uploads/r1vBdMO8n.png) ![](https://hackmd.io/_uploads/Byo3OzuIh.png) ## 程式碼練習一 //show dbs 是用於列出當前 MongoDB 伺服器上的所有資料庫。 show dbs //use mongo_class 用於切換到名為 mongo_class 的資料庫。 use mongo_class //db.student.insert() 是一個插入文檔的 MongoDB 命令,需要在 insert() 函數中提供一個包含要插入的文檔的對象。 db.student.insert([{ "profile":{"name":"林小宏","id":"108418005"}, "course":{ "110-1":[ {"course_id":"179729","course_name":"專題討論(A)","credits":1}, {"course_id":"187174","course_name":"數位影像處理","credits":3}, {"course_id":"179746","course_name":"軟硬體共同設計","credits":3}, {"course_id":"179787","course_name":"VLSI系統架構設計","credits":1}, {"course_id":"187670","course_name":"高等計算機視覺","credits":3} ] ,"110-2":[ {"course_id":"182495","course_name":"專題討論(A)","credits":1}, {"course_id":"182515","course_name":"資料庫系統","credits":3}, {"course_id":"190446","course_name":"數位電視設計","credits":3}, {"course_id":"190517","course_name":"最佳化概論","credits":3} ] } }, { "profile":{"name":"劉小賓","id":"108418006"}, "course":{ "110-1":[ {"course_id":"179729","course_name":"專題討論(A)","credits":1}, {"course_id":"187174","course_name":"數位影像處理","credits":3}, {"course_id":"187182","course_name":"互動式娛樂服務之音訊處理技術","credits":3}, {"course_id":"187656","course_name":"職場達人-自傳履歷與面試實務","credits":1}, {"course_id":"187670","course_name":"高等計算機視覺","credits":3} ], "110-2":[ {"course_id":"182495","course_name":"專題討論(A)","credits":1}, {"course_id":"182515","course_name":"資料庫系統","credits":3}, {"course_id":"190446","course_name":"數位電視設計","credits":3}, {"course_id":"190517","course_name":"最佳化概論","credits":3} ] } }] ) //show collections 是用於列出當前資料庫中的所有集合(collection)。 show collections //db.student.count():返回 student 集合中文檔的數量。 db.student.count() //返回當前所選擇的數據庫名稱。 db //db.student.drop() //將永久刪除整個集合及其所有文檔。 //db.dropDatabase() //將永久刪除當前數據庫及其所有集合和文檔。 //查詢並返回 student 集合中的所有文檔。 db.student.find({}) //將符合條件 { "profile.id": "108418005" } 的文檔進行更新,將其 profile 字段的值更新為 { name: "林林林", id: "123456789" }。 db.student.update({"profile.id":"108418005"},{$set:{profile:{name:"林林林",id:"123456789"}}}) //刪除符合條件 { "profile.id": "108418006" } 的文檔。 db.student.remove({"profile.id":"108418006"}) 單獨執行快捷鍵F6 整個程式一起執行F5(如果已經inser一個集合了會在原本的集合下新增一個集合) **滑鼠按右鍵 點選Refresh Selected Item** ![](https://hackmd.io/_uploads/SJKgPzdUh.png) ## 執行結果 ![](https://hackmd.io/_uploads/B1dguBOU2.png) ![](https://hackmd.io/_uploads/Skjm_HdU3.png) ![](https://hackmd.io/_uploads/rky3drdIn.png) ![](https://hackmd.io/_uploads/B1_8DBOI2.png) ## 程式碼練習二 show dbs use mongo_class db.test_data.insert([{'name': 'Anna', 'ages': 25, 'class': 'A', 'height': 150, 'weight': 44, 'score': 100, '_id': '001'}, {'name': 'Chad', 'ages': 21, 'class': 'A', 'height': 170, 'weight': 75, 'score': 85, '_id': '002'}, {'name': 'Ethan', 'ages': 42, 'class': 'A', 'height': 165, 'weight': 65, 'score': 90, '_id': '003'}, {'name': 'Amy', 'ages': 33, 'class': 'B', 'height': 144, 'weight': 50, 'score': 75, '_id': '004'}, {'name': 'Dory', 'ages': 12, 'class': 'C', 'height': 160, 'weight': 48, 'score': 88, '_id': '005'}, {'name': 'Allen', 'ages': 45, 'class': 'B', 'height': 180, 'weight': 80, 'score': 93, '_id': '006'}, {'name': 'Irving', 'ages': 25, 'class': 'C', 'height': 178, 'weight': 58, 'score': 60, '_id': '007'}]) db.getCollection('test_data').find({class:{$eq:'A'}}) // 查詢class等於'A'的文檔,$eq 來確定字段是否等於特定值 db.getCollection('test_data').find({class:'A'}) // 查詢class等於'A'的文檔 //查詢體重小於60的文檔: db.getCollection('test_data').find({weight:{$lt:60}}) //查詢名字不是'Chad'和'Ethan'的文檔: db.getCollection('test_data').find({name:{$nin:['Chad','Ethan']}}) //查詢分數大於等於80且體重小於80的文檔: db.getCollection('test_data').find({$and:[{score:{$gte:80}},{weight:{$lt:80}}]}) //查詢班級不是'B'且體重小於50的文檔: db.getCollection('test_data').find({$nor:[{class:'B'},{weight:{$lt:50}}]}) // 查詢存在class字段的文檔 db.getCollection('test_data').find({class:{$exists:true}}) // 查詢存在class字段且class屬於['B', 'C']的文檔 db.getCollection('test_data').find({$and:[{class:{$exists:true}},{class:{$in:['B','C']}}]}) // 查詢class為'A'或'C'且score在60到90之間的文檔 db.getCollection('test_data').find({$and:[{class:{$in:['A','C']}},{score:{$gte: 60, $lte: 90}}]}) // 查詢所有文檔 db.getCollection('test_data').find() //db.getCollection('test_data').find() //db.getCollection('test_data').find() //db.getCollection('test_data').find() ## 補充 ![](https://hackmd.io/_uploads/HyI0nKuUn.png) ![](https://hackmd.io/_uploads/Hy4ZTt_L2.png) ![](https://hackmd.io/_uploads/S1Pk9rOL3.png) ## 程式碼練習三 show dbs use mongo_class db.library.insert([{ _id:"4-1_1", book:"實用英文會話", price:299.0, authors: ["Jason", "hhhhh", "Bob"], borrower:{ name:"王小明", timestamp:ISODate("2015-07-23T12:00:00Z") } }, { _id:"4-1_2", book:"七天學會大數據資料庫處理-NoSQL:MongoDB入門與活用", price:360.0, authors: ["黃小嘉"], borrower:{name:"王小明", timestamp:ISODate("2015-07-24T12:30:00Z")} }, { _id:"4-1_3", book:"日本環球影城全攻略", price:280, authors: ["Jason", "Mary", "Bob"] }]) // 查詢價格小於等於 300 的library db.getCollection('library').find({price:{$lte: 300}}) // 查詢滿足以下條件之一的圖書: // 1. 作者中包含 'Bob' 和 'hhhhh' // 2. 存在借閱者信息 db.getCollection('library').find({$or:[{ authors: { $all: ['Bob', 'hhhhh'] } },{ borrower: { $exists: true } }]}) // 將書名為 '實用英文會話' 的圖書更新為 '英文大會話' db.library.update( { "book": "實用英文會話" },{ $set: { "book": "英文大會話" } }) // 將 ID 為 '4-1_2' 的圖書的作者更新為 ['黃小嘉', 'kim', 'hihi'] db.getCollection('library').update({"_id":"4-1_2"},{$set:{"authors":["黃小嘉","kim","hihi"]}}) // 保存(更新)ID 為 '4-1_2' 的圖書記錄,如果不存在則插入 db.getCollection('library').save({"_id":"4-1_2","authors":["黃小嘉","kim","hihi"]}) // 查詢書名中包含 'noSQL'(不區分大小寫)的圖書 db.library.find({ book:{$regex: /noSQL/, $options:"i"} }) //db.library.drop() ## 程式碼練習四 show dbs use mongo_class db.user_likes.insert([{"id":"1","name":"mark","age":25,"fans":100,"likes" : 1000}, {"id":"2","name":"steven","age":35,"fans":220,"likes" : 50}, {"id":"3","name":"stanly","age":30,"fans":120,"likes" : 33}, {"id":"4","name":"max","age":60,"fans":500,"likes" : 1000}, {"id":"5","name":"jack","age":30,"fans":130,"likes" : 1300}, {"id":"6","name":"crisis","age":30,"fans":130,"likes" : 100}, {"id":"7","name":"landry","age":25,"fans":130,"likes" : 100}]) // 查詢名字為 "mark" 的使用者,只返回 id 字段,排除 _id 字段 db.user_likes.find({ "name": "mark" }, { "id": 1,"_id":0 }) // 查詢滿足以下條件之一的使用者: // 1. 年齡介於 30 到 60 歲之間 // 2. 粉絲數量大於等於 200 db.getCollection('user_likes').find({$and:[{ age:{ $gte: 30, $lt: 60 } }, { fans: { $gte: 200 }}]}) // 查詢滿足以下條件之一的使用者: // 1. 粉絲數量小於等於 100 // 2. 喜歡數量小於 100 db.getCollection('user_likes').find({$or:[{fans: {$lte:100 }},{ like: { $lt: 100}}]}) // 查詢年齡為 25 或 60 歲的使用者 db.getCollection('user_likes').find({age:{ $in:[25,60]}}) // 查詢年齡既不是 25 也不是 60 歲的使用者,只返回 id 字段 db.getCollection('user_likes').find({age: { $nin:[25,60]}},{id:1}) // 查詢喜歡數量不大於 100 的使用者($not 運算符用於否定表達式) db.getCollection('user_likes').find({ likes: {$not:{$gt: 100} } }) // 插入一個新的記錄,名為 "mark",年齡為 23 db.user_likes.insert({"name":"mark","age": 23}) // 插入一個新的記錄,名為 "steven",年齡為 23 db.user_likes.insert({"name":"steven","age":23}) // 插入一個新的記錄,名為 "jj",年齡為 23 db.user_likes.insert({"name":"jj","age":23}) // 將名為 "mark" 的用戶的年齡更新為 18 db.user_likes.update({"name":"mark"},{$set:{age:18}}) // 插入一個新的記錄,ID 為 1,喜歡數為 0 db.user_likes.insert({"id":1,"likes":0}) // 將 ID 為 1 的用戶的喜歡數增加 1 db.user_likes.update({"id":1},{"$inc":{"likes":1}}) //db.user_likes.drop() ## 程式碼練習五 show dbs use mongo_class db.chat.insert([{ _id:"4-2_1", members: [ "Jason", "Bob" ], messages: [ { sender:"Jason", content:"Hello"}, { sender:"Bob", content:"Hi"}, { sender:"Jason", content:"午餐要吃什麼"}, { sender:"Jason", content:"吃義大利麵!?"}, { sender:"Bob", content:"走阿"} ] }, {_id:"4-2_2", members:[ "Jason", "Mary" ], messages:[]}, {_id:"4-2_3", members:[ "Bob", "Mary" ], messages:[]}]) // 查詢含有特定內容 "吃義大利麵" 的聊天記錄 db.getCollection('chat').find({messages: {$elemMatch: {content: /吃義大利麵/}}}) // 查詢沒有任何訊息的聊天記錄 db.getCollection('chat').find({messages:{$size:0}}) // 使用正則表達式查詢含有特定內容 "吃義大利麵" 的聊天記錄 db.chat.find({ messages: { $elemMatch: { content: { $regex: /吃義大利麵/ } } } }) ![](https://hackmd.io/_uploads/BkBZ7cOUn.png) ## 程式碼練習六 show dbs use mongo_class db.account.insert([{ "_id": "001", "name": "小明", "currency": [ { "type": "TWD", "cash": 1500, "lastModified": ISODate("2021-01-01T12:00:00Z") }, { "type": "USD", "cash": 9.99, "lastModified": ISODate("2021-01-02T12:00:00Z") } ] }, { "_id": "002", "name": "小華", "currency": [ { "type": "USD", "cash": 75.59, "lastModified": ISODate("2021-01-03T12:00:00Z") } ] }, { "_id": "003", "name": "小花", "currency": [] }]) // 更新帳戶 "小華" 中的 "USD" 貨幣類型為 "TWD",同時將現金數量乘以 30,並更新最後修改日期為當前日期 db.getCollection('account').update( { name: "小華", "currency.type": "USD" }, { $mul: { "currency.$.cash": 30 }, $set: { "currency.$.type": "TWD" }, $currentDate: { "currency.$.lastModified": { $type: "date" } } }, { multi: true, upsert: false } ) //db.account.drop() ## 程式碼練習七 show dbs use mongo_class db.school.insert([{ _id: "001", studentNumber: "102418099", studentName: "小明", score: 50}, { _id: "002", studentId: "102418098", studentName: "小華", score: 80}, { _id: "003", studentId: "102418097", studentName: "小花", score: 120}]) // 將 "studentNumber" 字段更名為 "studentid" db.getCollection('school').update({}, {$rename: {"studentNumber": "studentid"}}) // 將所有學生的 "score" 字段的值設置為 90,如果該字段的值大於 90,則保持不變 db.getCollection('school').update({},{$max: {score: NumberInt(90)}}) // 查詢學生記錄 db.getCollection('school').find({}) //db.school.drop() // 插入一個名為 "mark" 的用戶記錄,包含一個 "fans" 數組字段 db.fbuser.insert({ "name" : "mark", "fans" : ["steven","crisis","stanly"] }) // 向 "fans" 數組字段中添加多個元素 db.fbuser.update({"name":"mark"},{"$push":{"fans":{"$each":["jacky","lnadry","max"]}}}) // 向 "fans" 數組字段中添加多個元素,同時限制數組的大小為 4 db.fbuser.update({"name":"mark"},{"$push":{"fans":{"$each":["jacky","lnadry","max"],"$slice":4}}}) // 從 "fans" 數組字段中刪除最後一個元素 db.fbuser.update({"name":"mark"},{"$pop":{"fans":1}}) // 從 "fans" 數組字段中移除指定元素 "crisis" db.fbuser.update({"name":"mark"},{"$pull":{"fans":"crisis"}}) ## 牛刀小試(一) ![](https://hackmd.io/_uploads/HJ7Cw9uL3.png) show dbs use mongo_class db.school.insert([{ _id: "001", studentNumber: "102418099", studentName: "小明", score: 50}, { _id: "002", studentId: "102418098", studentName: "小華", score: 80}, { _id: "003", studentId: "102418097", studentName: "小花", score: 120}]) // 將 "studentNumber" 字段更名為 "studentId" db.getCollection('school').update({}, {$rename: {"studentNumber": "studentId"}}) // 將 "score" 字段的值大於 100 的記錄的 "score" 字段值設置為 100 db.getCollection('school').update({"score": {"$gt": 100}}, {"$set": {"score": 100}}) //將它們的score字段的值設置為100,但只有當原始值小於100時才進行更新。 db.getCollection('school').update({},{$min:{"score":NumberInt(100)}}, {multi:true}) // 插入一個集合 "number_group",包含一個文檔 db.number_group.insert([{_id:"4-9_01", name:"江小于", age:22, phone:"0967-481-146"}, {_id:"4-9_02", name:"穆小蓉", age:18, phone:"0989-153-149"}, {_id:"4-9_03", name:"陳小昇", age:24, phone:"0955-581-064"}, {_id:"4-9_04", name:"傅小彰", age:25, phone:"0967-058-845"}, {_id:"4-9_05", name:"廖小健", age:28, phone:"0989-758-138"}, {_id:"4-9_06", name:"陳小翰", age:31, phone:"0989-051-129"}, {_id:"4-9_07", name:"鄭小瀚", age:27, phone:"0967-984-852"}, {_id:"4-9_08", name:"梁小瑋", age:21, phone:"0989-748-913"}, {_id:"4-9_09", name:"陳小鴻", age:22, phone:"0955-685-846"}, {_id:"4-9_10", name:"陳小豪", age:20, phone:"0955-648-843"}]) // 插入一個包含數組字段 "list" 的文檔 db.number_group.insert({_id:"001",list:[30,40,50]}) // 向 "list" 數組字段中添加一個元素 80 db.number_group.update({ _id: "001" }, { $push: { list: NumberInt(80) } }, {multi:true, upsert:false}) //db.number_group.update({ _id: "001" }, { $push: { list: 60 } }) // 將多個元素 [60, 60, 70] 添加到 "list" 數組字段中 db.number_group.update({ _id: "001" }, { $push: { list: { $each: [60, 60, 70] } } }, {multi:true, upsert:false}) // 從 "list" 數組字段中刪除最後一個元素 db.number_group.update({ _id: "001" }, { $pop: { list: 1 } }, {multi:true, upsert:false}) // 從 "list" 數組字段中刪除第一個元素 db.number_group.update({_id: "001"}, { $pop: { list: -1 } }, {multi:true, upsert:false}) // 從 "list" 數組字段中移除所有值為 60 的元素 db.number_group.update({_id: "001"}, { $pull: { list: 60 } }, {multi:true, upsert:false}) db.number_group.drop() ## 牛刀小試(二) ![](https://hackmd.io/_uploads/Bk0RwcdLn.png) // 將多個文檔插入到 "drink" 集合中 db.drink.insert([ { _id: "001", product: "日月潭紅茶", type: "tea", price: {M:20,L:30}, sold:0, log:[] }, { _id: "002", product: "金鑽鳳梨綠", type: "fruit", price: {M:40,L:50}, sold:0, log:[] }, { _id: "003", product: "黑糖粉圓鮮奶", type: "tea latte", price: {M:50,L:65}, sold:0, log:[] } ]) // 對 _id 為 "001" 的文檔進行更新,增加 sold 字段的值 20,同時將一個新的對象 {time: Date.now(), size: 'M'} 添加到 log 字段的陣列中。使用 $push 操作符將對象添加到陣列的末尾。 upsert 設置為 false,表示如果文檔不存在則不進行插入。 db.drink.update({ _id: "001" },{$inc: { sold: 20 },$push: { log: {time:Date.now(),size:'M'} } },{upsert:false}) db.drink.update({ _id: "002" },{$inc: { sold: 40 },$push: { log: {time:Date.now(),size:'M'} } },{upsert:false}) db.drink.update({ _id: "003" },{$inc: { sold: 65 },$push: { log: {time:Date.now(),size:'L'} } },{upsert:false}) // 刪除 "drink" 集合中的所有文檔 db.drink.drop() ![](https://hackmd.io/_uploads/SygTLcdI2.png) ![](https://hackmd.io/_uploads/BJHSv9OL2.png) ![](https://hackmd.io/_uploads/H1t8v9dUh.png) ![](https://hackmd.io/_uploads/HJfdwqOL3.png) ![](https://hackmd.io/_uploads/S1_FP5OIn.png) ![](https://hackmd.io/_uploads/B1h9vqOUh.png) ![](https://hackmd.io/_uploads/HJR3v5OIn.png) ## 牛刀小試(三) ![](https://hackmd.io/_uploads/BJKku5u83.png) use mongo_class db.contacts.insert([{_id:"4-9_01", name:"江小于", age:22, phone:"0967-481-146"}, {_id:"4-9_02", name:"穆小蓉", age:18, phone:"0989-153-149"}, {_id:"4-9_03", name:"陳小昇", age:24, phone:"0955-581-064"}, {_id:"4-9_04", name:"傅小彰", age:25, phone:"0967-058-845"}, {_id:"4-9_05", name:"廖小健", age:28, phone:"0989-758-138"}, {_id:"4-9_06", name:"陳小翰", age:31, phone:"0989-051-129"}, {_id:"4-9_07", name:"鄭小瀚", age:27, phone:"0967-984-852"}, {_id:"4-9_08", name:"梁小瑋", age:21, phone:"0989-748-913"}, {_id:"4-9_09", name:"陳小鴻", age:22, phone:"0955-685-846"}, {_id:"4-9_10", name:"陳小豪", age:20, phone:"0955-648-843"}]) db.contacts.drop() // 查找名字以 "陳" 開頭並且電話包含 "0955" 的文檔,並按年齡升序排序 db.contacts.find({ name: /^陳/, phone: /0955/ }).sort({ age: 1 })