MongoDB安裝、配置以及操作介紹

1. 簡介

  1. 數(shù)據(jù)庫分類
    (1)關(guān)系型數(shù)據(jù)庫,是指采用了關(guān)系模型來組織數(shù)據(jù)的數(shù)據(jù)庫。關(guān)系型數(shù)據(jù)庫遵循ACID規(guī)則。
    (2)非關(guān)系型的數(shù)據(jù)庫(NoSQL-Not Only SQL)是對不同于傳統(tǒng)的關(guān)系型數(shù)據(jù)庫的數(shù)據(jù)庫管理系統(tǒng)的統(tǒng)稱。
    參考: 關(guān)系型數(shù)據(jù)庫和非關(guān)系型數(shù)據(jù)庫區(qū)別、oracle與mysql的區(qū)別
  2. MongoDB 將數(shù)據(jù)存儲為一個文檔,數(shù)據(jù)結(jié)構(gòu)由鍵值(key=>value)對組成。
  3. MongoDB 文檔類似于 JSON對象。字段值可以包含其他文檔,數(shù)組及文檔數(shù)組。
  4. 數(shù)據(jù)庫對比
SQL術(shù)語/概念 MongoDB術(shù)語/概念 解釋/說明
database database 數(shù)據(jù)庫
table collection 數(shù)據(jù)庫表/集合
row document 數(shù)據(jù)記錄行/文檔
column field 數(shù)據(jù)字段/域
index index 索引
table joins 表連接,MongoDB不支持
primary key primary key 主鍵,MongoDB自動將_id字段設(shè)置為主鍵
  • 一個服務(wù)可以創(chuàng)建多個database數(shù)據(jù)庫。
  • 一個數(shù)據(jù)庫database可以由多個集合collection組成。
  • 一個集合collection一般由多個同類型文檔document組成。
  • 一個文檔document由多個field字段組成。
  • index索引以及_id主鍵是對文檔document的標識。

2. 安裝

2.1 MongoDB安裝及啟動

  1. 路徑
    (1) 安裝目錄
    /usr/local/Cellar/mongodb/4.0.4_1
    (2) 配置文件目錄
    /usr/local/etc/mongod.conf
    注釋: 配置文件中有數(shù)據(jù)庫目錄和日志輸出文件目錄。
    (3) 日志輸出文件目錄
    /usr/local/var/log/mongodb/mongo.log
    (4) 數(shù)據(jù)庫目錄
    /usr/local/var/mongodb
    注釋: admin數(shù)據(jù)庫是存放管理員信息的數(shù)據(jù)庫。
  2. mongod.conf配置文件
systemLog:
  destination: file
  # 日志文件路徑
  path: /usr/local/var/log/mongodb/mongo.log
  # 日志是累加而不是覆蓋
  logAppend: true
storage:
  # 數(shù)據(jù)庫存儲路徑
  dbPath: /usr/local/var/mongodb
net:
  #port: 19999 綁定端口,如果不填,則表示27017端口
  # 綁定ip, 如果要綁定多個ip,可以用數(shù)組表示
  bindIp: 127.0.0.1

注意:①如果綁定0.0.0.0,則所有客戶端都能夠訪問(即使不配置bindIp,外網(wǎng)仍無法訪問)。 ② 如果mongod.conf文件中綁定了ip,則只有綁定的ip對應(yīng)的客戶端才能夠訪問。

  1. 啟動
    (1) 開啟MongoDB服務(wù)
    mongod -f /usr/local/etc/mongod.conf
    地址:http://localhost:27017/
    注釋: 可以修改MongoDB默認27017端口
    注意:如果無法開啟,則嘗試通過刪除重建數(shù)據(jù)庫目錄的方式解決①rm -rf /usr/local/var/mongodbmkdir /usr/local/var/mongodb
    (2) 客戶端連接服務(wù)端
    mongo
  2. 關(guān)閉MongoDB服務(wù)
    mongo
    use admin;
    db.shutdownServer();
    注釋: 只有在admin數(shù)據(jù)庫中時才能關(guān)閉MongoDB服務(wù)。
  3. 安裝路徑下的exe程序介紹
    (1) mongo.exe 客戶端, 支持js語法!
    (2) mongod.exe 服務(wù)端
    (3) mongodump.exe 備份工具
    (4) mongorestore.exe 恢復工具
    (5) mongoexport.exe 導出工具
    (6) mongoimport.exe 導入工具
    (7) mongostat.exe 實時性能監(jiān)控工具
    (8) mongotop.exe 跟蹤MongDB實例讀寫時間工具
    注釋: mongo.exe客戶端工具和mongod.exe服務(wù)端工具最常用。

2.2 MongoDB圖形客戶端

  1. Robo 3T是目前最好的可視化MongoDB客戶端,并且是免費的。
    image.png
  2. Robomongo公司還提供了功能更強大的Studio 3T客戶端,該軟件為商業(yè)軟件。
    該軟件支持SQL語句查詢,Studio 3T會幫我們轉(zhuǎn)化為mongo查詢語句。
    image.png

3. 操作

3.1 mongo.exe客戶端

3.1.1 操作用戶

3.1.1.1 創(chuàng)建用戶

  1. 創(chuàng)建root用戶
 # 非認證啟動
 mongod -f /usr/local/etc/mongod.conf 
# 新開窗口進入shell終端
?  ~ mongo
# 查看已有數(shù)據(jù)庫
> show dbs 
# 查看/切換到admin數(shù)據(jù)庫
> use admin
switched to db admin
# 創(chuàng)建root用戶,指定用戶名、密碼、角色和數(shù)據(jù)庫
> db.createUser({user: 'root', pwd: 'root', roles:[{role: 'userAdminAnyDatabase', db: 'admin'}]})
Successfully added user: {
    "user" : "root",
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        }
    ]
}

注釋: ① 建立了 userAdminAnyDatabase 角色,用來管理用戶,可以通過這個角色來創(chuàng)建、刪除用戶。② userAdminAnyDatabase權(quán)限只是針對用戶管理的,對其他(數(shù)據(jù)庫讀寫等)是沒有權(quán)限的。
注意: ① 用戶與數(shù)據(jù)庫是綁定的,在某一個數(shù)據(jù)庫里創(chuàng)建的用戶只能夠在該數(shù)據(jù)庫中進行認證。② 一般只創(chuàng)建操作當前數(shù)據(jù)庫的用戶(db填當前數(shù)據(jù)庫),如果創(chuàng)建了操作其他數(shù)據(jù)庫的用戶,則需要在用戶創(chuàng)建庫中進行認證,然后再去其他數(shù)據(jù)庫中操作 ③ 以非認證的方式啟動數(shù)據(jù)庫則不需要用戶權(quán)限。

  1. 通過root用戶創(chuàng)建其他用戶
 # 認證啟動
mongod -config /usr/local/etc/mongod.conf --auth
# 新開窗口進入shell終端
?  ~ mongo
> show dbs 
# Error 報錯。沒有驗證,所以沒有權(quán)限。
> use admin  #驗證,因為在admin下面添加的帳號,所以要到admin下面驗證。
switched to db admin
> db.auth('root', 'root')
1
> show dbs
# 展示所有數(shù)據(jù)庫
> use test  #在test庫里創(chuàng)建帳號
switched to db test
> db.createUser({user: 'test', pwd: 'test', roles: [{role: 'readWrite', db: 'test'}]})
> show users #查看當前庫下的用戶

注釋: ① --auth代表授權(quán)啟動,需要帳號密碼才能訪問。auth=true可以加到mongo.conf配置文件里面去進行統(tǒng)一管理。② 以非認證的方式啟動mongoDB也可以創(chuàng)建用戶,創(chuàng)建過程與創(chuàng)建root用戶相同。

  1. 用戶角色分類
  • 數(shù)據(jù)庫用戶角色:readreadWrite;
  • 數(shù)據(jù)庫管理角色:dbAdmin、dbOwner、userAdmin;
  • 集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
  • 備份恢復角色:backuprestore;
  • 所有數(shù)據(jù)庫角色:readAnyDatabasereadWriteAnyDatabase、userAdminAnyDatabasedbAdminAnyDatabase
  • 超級用戶角色:root
  • 內(nèi)部角色:__system
  1. 具體角色權(quán)限
  • Read:允許用戶讀取指定數(shù)據(jù)庫
  • readWrite:允許用戶讀寫指定數(shù)據(jù)庫
  • dbAdmin:允許用戶在指定數(shù)據(jù)庫中執(zhí)行管理函數(shù),如索引創(chuàng)建、刪除,查看統(tǒng)計或訪問system.profile
  • userAdmin:允許用戶向system.users集合寫入,可以找指定數(shù)據(jù)庫里創(chuàng)建、刪除和管理用戶
  • clusterAdmin:只在admin數(shù)據(jù)庫中可用,賦予用戶所有分片和復制集相關(guān)函數(shù)的管理權(quán)限。
  • readAnyDatabase:只在admin數(shù)據(jù)庫中可用,賦予用戶所有數(shù)據(jù)庫的讀權(quán)限
  • readWriteAnyDatabase:只在admin數(shù)據(jù)庫中可用,賦予用戶所有數(shù)據(jù)庫的讀寫權(quán)限
  • userAdminAnyDatabase:只在admin數(shù)據(jù)庫中可用,賦予用戶所有數(shù)據(jù)庫的userAdmin權(quán)限
  • dbAdminAnyDatabase:只在admin數(shù)據(jù)庫中可用,賦予用戶所有數(shù)據(jù)庫的dbAdmin權(quán)限。
  • root:只在admin數(shù)據(jù)庫中可用。超級賬號,超級權(quán)限(不建議使用)。
  1. Studio 3T創(chuàng)建用戶
    image.png
3.1.1.2 授權(quán)認證
 # 認證啟動
mongod -config /usr/local/etc/mongod.conf --auth
# 新開窗口進入shell終端
?  ~ mongo

# root用戶授權(quán)驗證
> use admin 
switched to db admin
> show dbs # 報錯,沒有權(quán)限
> db.auth('root', 'root') # 授權(quán)用戶
> show dbs # 成功,展示所有數(shù)據(jù)庫

# test用戶授權(quán)驗證
> use test
> show tables # 報錯,沒有權(quán)限
> db.auth('test', 'test') # 授權(quán)用戶
> show tables  # 成功,展示當前數(shù)據(jù)庫中所有表
3.1.1.3 查看/刪除用戶
> mongo 
# 操作所有用戶只在admin數(shù)據(jù)庫中可用
> use admin 
switched to db admin
> db.auth('root','root') # 授權(quán)認證
> show users #查看當前數(shù)據(jù)庫中的用戶
> db.system.users.find().pretty()  #查看所有數(shù)據(jù)庫中的用戶
{
    "_id" : "admin.root",
    "user" : "root",
    "db" : "admin",
    "credentials" : {
        "SCRAM-SHA-1" : {
            "iterationCount" : 10000,
            "salt" : "myPBMNr+71D/BHR2KNIs7g==",
            "storedKey" : "ar4RsCe/Mn0rm3DpCscUtLJy32Q=",
            "serverKey" : "fbZ69Fo+IPMxFCznNIW2rZJqoDU="
        }
    },
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        }
    ]
}
> db.system.users.find().count()
1
> db.system.users.remove({user:"root"})
WriteResult({ "nRemoved" : 1 })
> db.system.users.find().count()
0

3.1.2 操作數(shù)據(jù)庫

3.1.2.1 數(shù)據(jù)結(jié)構(gòu)
  1. MongoDB使用BSON(二進制JSON)來保存數(shù)據(jù)。一條記錄就是一個BSON,被稱作文檔(Document)。
  2. 某些BSON聚集在一起,就形成集合(Collection)。
3.1.2.2 查詢
  1. 查看所有數(shù)據(jù)庫
    show dbs
  2. 新建/切換到數(shù)據(jù)庫
    use test
    注釋: 只有在插入表數(shù)據(jù)之后才真正實現(xiàn)數(shù)據(jù)庫的創(chuàng)建。
  3. 查看當前數(shù)據(jù)庫
    db
    注釋: db表示當前數(shù)據(jù)庫。
  4. 查看集合
    show collections/tables
  5. 查看集合占用內(nèi)存
    db.集合名.dataSize()
  6. 查看當前集合所有數(shù)據(jù)
    db.集合名.find()
  7. 格式化查看當前集合所有數(shù)據(jù)
    db.集合名.find().pretty()
  8. 查看集合中第一條數(shù)據(jù)
    db.集合名.findOne()
  9. 限制數(shù)量
    db.集合名.find().limit(數(shù)量)
  10. 跳過指定數(shù)量
    db.集合名.find().skip(數(shù)量)
  11. 查詢數(shù)量
    db.表名.find().count()
  12. 排序
    db.表名.find().sort({"字段名":1}) //1表示升序; -1表示降序
  13. 指定字段返回
    db.表名.find({},{"字段名":0}) //1返回; 0不返回
  14. 比較查詢
    大于- $gt;小于- $lt;大于等于- $gte;小于等于- $lte;非等于- $ne;包含- $in;不包含- $nin;
> for(let i = 0; i < 10; i++) {
     db.tb.save({'name': 'jake'+ i, id: i, msg: {age:i}})
     //mongo.exe 客戶端, 支持js語法!
  }
> db.tb.find()   
0-10
> db.tb.find({'id': 3})
3
> db.tb.find({'msg.age': 6})
6
> db.tb.find().limit(3)
0-2
> db.tb.find().limit().skip(2).limit(2)
2、3
> db.tb.find({'msg.age': {'$gt':7}})
8、9
> db.tb.find({'id': {'$lt':3, '$gte':1}})
1、2 
> db.tb.find({'id': {'$ne':3}})
0-2、4-9
> db.tb.find({'$or': [{'id':3}, {'name': 'jake7'}]})
3、7
> db.tb.find({'id': {'$in': [2,4]}});
2、4
> db.tb.find({'id': {'$nin': [1,3,5,7,9]}});
0、2、4、6、8
> db.tb.find({'id': {'$gt':2}}).count()
7
> db.tb.find({'msg.age': {'$lte':6}}).sort({id: -1}).limit(2);
6、5
> db.tb.find({id: {'$gte': 6}}, {msg: 0})
{ "_id" : ObjectId("5b559f72e1aefaf030c8d016"), "name" : "jake6", "id" : 6 }
{ "_id" : ObjectId("5b559f72e1aefaf030c8d017"), "name" : "jake7", "id" : 7 }
{ "_id" : ObjectId("5b559f72e1aefaf030c8d018"), "name" : "jake8", "id" : 8 }
{ "_id" : ObjectId("5b559f72e1aefaf030c8d019"), "name" : "jake9", "id" : 9 }
  1. 高級查詢
    全部 - $all;全不 - $not;或者 - $or;含有字段 - $exists
    注釋:$all$in類似,$in只需滿足()內(nèi)的某一個值即可, 而$all 必須滿足[]內(nèi)的所有值。
for(let i = 0; i < 10; i++) {
     db.tb.save({'name': 'jake'+ i, id: i, msg: {age:i}})
  }

db.tb.find({'msg.age': {'$all': [3]}}) //3
db.tb.find({'$or': [{'name': 'jake1'}, {'msg.age': 3}]}) //1 3
db.tb.find({'msg.age': {'$not': {'$gte': 3}}}) //0-2
db.tb.find({'msg.age': {'$exists': 1}}) //0-9
  1. 正則表達式
    /匹配字符/new RegExp("匹配字符")
> for(let i = 0; i < 10; i++) {
     db.tb.save({'name': 'jake'+ i, id: i, msg: {age:i}})
  }
> db.tb.find({name: /^jake(1|2)$/})
{ "_id" : ObjectId("5b559f72e1aefaf030c8d011"), "name" : "jake1", "id" : 1, "msg" : { "age" : 1 } }
{ "_id" : ObjectId("5b559f72e1aefaf030c8d012"), "name" : "jake2", "id" : 2, "msg" : { "age" : 2 } }
  1. 排除重復
for(let i = 0; i < 10; i++) {
     db.tb.save({'name': 'jake'+ i, id: i, msg: {age:i}})
}

db.tb.save(arr)
db.tb.find()  //0-9
db.tb.distinct('name') // ['jack']
3.1.2.3 增加
  1. 新增數(shù)據(jù)庫表
    db.createCollection('user')
    注釋:一個集合相當于一個表。
  2. 創(chuàng)建集合并插入數(shù)據(jù)
    (1) 使用insert方法插入一條數(shù)據(jù)
    db.user.insert({id:1, name:'hello'})
    (2) 使用save方法插入一條數(shù)據(jù)
    db.user.save({id:2, name:'mongo'})
    (3) 插入數(shù)據(jù)時指定_id
    db.user.insert({_id: 0, id:1, name:'hello'})
    db.save.insert({_id: 0, id:1, name:'hello'})
    注意: ① 如果已有user表則在該表中插入一條數(shù)據(jù),如果沒有user表則創(chuàng)建user表并插入一條數(shù)據(jù)。② 如果未指定_id,則mongodb會給該條數(shù)據(jù)默認生成_id。③ 如果指定的_id與已有某條數(shù)據(jù)的_id相同,則sava方法更新數(shù)據(jù),insert方法拋出異常。
2.1.2.4 刪除
  1. 刪除當前數(shù)據(jù)庫
    db.dropDatabase()
  2. 刪除數(shù)據(jù)庫表
    db.表名稱.drop()
  3. 刪除表中某一條數(shù)據(jù)
    db.表名.remove(條件);
> db.tb.remove({id: {$gt: 5}})
3.1.2.5 修改
  1. 更新集合名稱
    db.表名.renameCollection(修改之后的名稱)
db.tb.renameCollection('tb1')
  1. 更新集合中某一條數(shù)據(jù)
    db.表名.update({查詢條件},{$set:{要修改的字段名:修改后的字段值}});
> db.tb.update({name: 'jake0'}, {$set: {'msg.age': 6}});
> db.tb.update({'msg.age': 5}, {$set: {'id': 10}})

注釋:update方法的第一個參數(shù)起到查詢的效果,更新查詢到的某一條數(shù)據(jù)。

  1. 更新集合中所有查詢到的數(shù)據(jù)
    db.表名.updateMany({查詢條件},{$set:{要修改的字段名:修改后的字段值}});
db.tb.updateMany({'msg.age': {$gte: 0}}, {$set: {'msg.age': 0}})
  1. 刪除記錄中的字段
    db.表名.updateMany({查詢條件},{$unset:{字段1:1, 字段2: 1}});
db.tb.updateMany({}, {$unset: {id: 1}})
  1. 對某個字段做加法運算
    db.表名.updateMany({查詢條件},{$inc:{字段1:增加的值}});
db.tb.updateMany({}, {$inc: {'msg.age': 6}})
  1. 數(shù)組中添加元素、刪除元素
    db.表名.updateMany({查詢條件},{$push:{數(shù)組字段:數(shù)組中添加的元素}});
    db.表名.updateMany({查詢條件},{$pull:{數(shù)組字段:數(shù)組中刪除的元素}});
db.teacher.save({name: 'jack', role: ['老師', '班主任']})
db.teacher.updateMany({name: 'jack'}, {$push: {role: '教務(wù)主任'}})
db.teacher.updateMany({name: 'jack'}, {$pull: {role: '老師'}})
3.1.2.6 索引機制
  1. MongoDB存放了大量的數(shù)據(jù),為了加快數(shù)據(jù)檢索速度,需要為集合創(chuàng)建索引。
    (1) 創(chuàng)建索引
    db.collection.createIndex({字段, 1}, options)
    如果索引字段值按照升序排列屬性值為1,降序排列屬性值為-1
    (2) 刪除索引
    db.collection.dropIndexes()
    (3) 獲取索引
    db.collection.getIndexes()
    (4) 空閑時創(chuàng)建索引
    {background: true}
    由于創(chuàng)建索引會阻塞MongoDB,一般在空閑時創(chuàng)建索引。
    (5) 自定義索引名稱
    {name: "名稱"}
    默認使用索引字段_1/-1做為索引名稱。
    (6) 唯一性索引
    {unique: true}
    唯一性索引只能創(chuàng)建在每個記錄都含有的公共字段上。
for(let i = 0; i < 10; i++) {
     db.tb.save({'name': 'jake'+ i, id: i, msg: {age:i}})
}
db.tb.createIndex({name: 1})
db.tb.dropIndexes()
db.tb.createIndex({name: 1}, {background: true, name: 'name', unique:true})
db.tb.getIndexes() //_id_ name
db.tb.save({'name': 'jake1', id: 1, msg: {age:1}}) 
//E11000 duplicate key error collection: school.tb index: name dup key: { : "jake1" }
  1. 創(chuàng)建索引的原則
    集合的數(shù)據(jù)量很大,則應(yīng)該創(chuàng)建索引。
    集合的數(shù)據(jù)讀取多于寫入,則應(yīng)該創(chuàng)建索引。
    給經(jīng)常被當做查詢條件的字段設(shè)置索引。

3.1.2.7 數(shù)據(jù)導入導出

  1. mongoexport導出集合
    (1) 未授權(quán)認證
    mongoexport -d(指定數(shù)據(jù)庫) demo -c(指定表名稱) user -q(過濾條件,可以省略) ‘{“name”: {$ne: null}}’ -o(導出文件名)
    (2) 已授權(quán)認證
?  ~ mongoexport --host=localhost --port=27017 -u school -p school --authenticationDatabase=school -d school -c tb -o /Users/nimengwei/Downloads/tb.json

2020-02-08T12:18:59.114+0800    connected to: localhost:27017
2020-02-08T12:18:59.123+0800    exported 10 records
  1. mongoimport導入集合
    (1) 未授權(quán)認證
    mongoimport --host 127.0.0.1:19999 -d(指定數(shù)據(jù)庫) demo -c(指定表名稱) user --file ./dbbackup/dumall-backup/user.json
    (2) 已授權(quán)認證
?  ~ mongoimport --host=localhost --port=27017 -u school -p school --authenticationDatabase=school -d school -c tbcopy --file /Users/nimengwei/Downloads/tb.json
2020-02-08T12:30:55.498+0800    connected to: localhost:27017
2020-02-08T12:30:55.586+0800    imported 10 documents
  1. mongodump導出邏輯庫
    --dumpDbUsersAndRoles參數(shù)可以備份隸屬于邏輯庫的用戶
?  ~ mongodump --host=localhost --port=27017 -u school -p school --authenticationDatabase=school -d school -o /Users/nimengwei/Downloads/ 
2020-02-08T15:54:41.616+0800    writing school.tb to 
2020-02-08T15:54:41.616+0800    writing school.tbcopy to 
2020-02-08T15:54:41.616+0800    writing school.teacher to 
2020-02-08T15:54:41.616+0800    writing school.stu to 
2020-02-08T15:54:41.650+0800    done dumping school.tb (10 documents)
2020-02-08T15:54:41.650+0800    done dumping school.tbcopy (10 documents)
2020-02-08T15:54:41.651+0800    done dumping school.stu (1 document)
2020-02-08T15:54:41.653+0800    done dumping school.teacher (2 documents)
  1. mongorestore導入邏輯庫
    --drop 已有的數(shù)據(jù)集合是否刪除
?  ~ mongorestore --host=localhost --port=27017 -u school -p school --authenticationDatabase=school --drop -d school /Users/nimengwei/Downloads/school
2020-02-08T16:03:30.670+0800    the --db and --collection args should only be used when restoring from a BSON file. Other uses are deprecated and will not exist in the future; use --nsInclude instead
2020-02-08T16:03:30.671+0800    building a list of collections to restore from /Users/nimengwei/Downloads/school dir
2020-02-08T16:03:30.688+0800    reading metadata for school.tb from /Users/nimengwei/Downloads/school/tb.metadata.json
...
2020-02-08T16:03:30.984+0800    done

3.2 Node操作數(shù)據(jù)庫

3.2.1 增刪改查

3.2.1.1 增加
  1. 創(chuàng)建集合
const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://127.0.0.1:27017';

MongoClient.connect(url, (err, client) => {
    console.log('連接成功!');
    const db = client.db('test');
    db.createCollection('tb1', function (err, res) {
        if (err) throw err;
        console.log("創(chuàng)建tb1集合!");
        client.close();
    });
});
  1. 創(chuàng)建集合并插入數(shù)據(jù)
const MongoClient = require('mongodb').MongoClient;

const DB_CONN_STR = 'mongodb://127.0.0.1:27017';

MongoClient.connect(DB_CONN_STR, (err, client) => {
    console.log('連接成功!');
    const db = client.db('test');
    const collection = db.collection('tb2');
    const data = [
        {name: 'wilson01', age: 18},
        {name: 'wilson02', age: 20}
    ];
    collection.insert(data, (err, result) => {
        if(err) {
            console.log('Err' + err);
            return;
        } else {
            console.log(result);
            client.close();
            //{ result: { ok: 1, n: 2 },
            //   ops:
            //    [ { name: 'wilson01', age: 18, _id: 5b55de761ffbb2ac7f041dcf },
            //      { name: 'wilson02', age: 20, _id: 5b55de761ffbb2ac7f041dd0 } ],
            //   insertedCount: 2,
            //   insertedIds: { '0': 5b55de761ffbb2ac7f041dcf, '1': 5b55de761ffbb2ac7f041dd0 }
            // }
        }
    })
});

注釋: insert()方法既能夠插入一條又能夠插入多條數(shù)據(jù); insertOne()方法只能夠插入一條數(shù)據(jù);insertMany()方法可以插入多條數(shù)據(jù)。

3.2.1.2 查詢
  1. 簡單查詢
const MongoClient = require('mongodb').MongoClient;

const DB_CONN_STR = 'mongodb://127.0.0.1:27017';

const selectedData = (client, callback) => {
    const db = client.db('test');
    const collection = db.collection('tb2');
    const whereStr = {age: 20};
    collection.find(whereStr).toArray((err, result) => {
        if(err) {
            console.log('Err' + err);
            return;
        } else {
            callback(result);
            //[{ _id: 5b55de761ffbb2ac7f041dd0, name: 'wilson01', age: 20 }]
        }
    })
};

MongoClient.connect(DB_CONN_STR, (err, client) => {
    console.log('連接成功!');
    selectedData(client, (result) => {
        console.log(result);
        client.close();
    });
});
  1. 條件查詢
const MongoClient = require('mongodb').MongoClient;

const DB_CONN_STR = 'mongodb://127.0.0.1:27017';

const selectedData = (client, callback) => {
    const db = client.db('test');
    const collection = db.collection('tb');
    //查詢所有
    collection.find().toArray((err, result) => {
        if(err) throw  err;
        callback(result);
        //1,2,3,4,5
    })
    //正則查詢
    collection.find({name: /^jake(1|2)$/}).toArray((err, result) => {
        if(err) throw  err;
        callback(result);
        //1,2
    })
    //查詢排序
    collection.find({id: {$gt: 2}}).sort({id: -1}).toArray((err, result) => {
        if(err) throw  err;
        callback(result);
        //5, 4, 3
    })
    //查詢分頁
   collection.find({id: {$ne: 3}}).limit(3).toArray((err, result) => {
        if(err) throw  err;
        callback(result);
        //1, 2, 4
    })
    //查詢跳頁
    collection.find().skip(2).toArray((err, result) => {
        if(err) throw  err;
        callback(result);
        //3, 4,5
    })
};

MongoClient.connect(DB_CONN_STR, (err, client) => {
    selectedData(client, (result) => {
        console.log(result);
        client.close();
    });
});

注釋: 支持mongo命令終端支持的查詢語句。

3.2.1.3 修改
const MongoClient = require('mongodb').MongoClient;

const DB_CONN_STR = 'mongodb://127.0.0.1:27017';

const updateData = (client, callback) => {
    const db = client.db('test');
    const collection = db.collection('tb2');
    const whereStr = {name: 'wilson01'};
    const updateStr = {$set: {age: 28}};
    collection.updateMany(whereStr, updateStr, (err, result) => {
        if(err) {
            console.log('Err' + err);
            return;
        } else {
            callback(result);
        }
    })
};

MongoClient.connect(DB_CONN_STR, (err, client) => {
    console.log('連接成功!');
    updateData(client, (res) => {
        console.log(res.result.nModified + " 條文檔被更新");
        //1 條文檔被更新
        client.close();
    });
});

注釋: ① updateOne()方法只會更新第一個符合條件的數(shù)據(jù)。 updateMany()方法會更新所有符合條件的數(shù)據(jù)。② res.result.nModified 為被更新的條數(shù)。

3.2.1.4 刪除
  1. 刪除集合
const MongoClient = require('mongodb').MongoClient;

const DB_CONN_STR = 'mongodb://127.0.0.1:27017';

const delData = (client, callback) => {
    const db = client.db('test');
    const collection = db.collection('tb2');
    collection.drop((err, result) => {
        if(err) throw  err;
        callback(result)
    })
};

MongoClient.connect(DB_CONN_STR, (err, client) => {
    console.log('連接成功!');

    delData(client, (res) => {
        console.log(res);
        client.close();
    });
});
  1. 刪除查詢到的數(shù)據(jù)
const MongoClient = require('mongodb').MongoClient;

const DB_CONN_STR = 'mongodb://127.0.0.1:27017';

const delData = (client, callback) => {
    const db = client.db('test');
    const collection = db.collection('tb2');
    const whereStr = {name: 'wilson01'};
    collection.deleteOne(whereStr, (err, result) => {
        if(err) {
            console.log('Err' + err);
            return;
        } else {
            callback(result);
        }
    })
};

MongoClient.connect(DB_CONN_STR, (err, client) => {
    console.log('連接成功!');

    delData(client, (res) => {
        console.log(res.result.n + " 條文檔被刪除");
        //1 條文檔被刪除
        client.close();
    });
});

注釋: ① deleteOne()方法會刪除第一條符合條件的數(shù)據(jù)。deleteMany() 方法會刪除所有符合條件的數(shù)據(jù)。② res.result.n 刪除的條數(shù)。

4. 參考

MongoDB中文文檔
Mac環(huán)境下安裝和配置MongoDB
mac系統(tǒng)下安裝、啟動、停止mongodb
MongoDB 3.0 用戶創(chuàng)建

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容