每日一句
There should be a better way to start a day than waking up every morning.
應該有更好的方式開始新一天, 而不是千篇一律的在每個上午醒來。
數據庫操作
查詢數據庫
查看所有數據庫
查看所有數據庫,可以使用 show dbs
或者 show databases
命令
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> show databases
查看當前的數據庫
查看當前的數據庫名:db
命令
> db
test
>
創建或切換數據庫
語法
MongoDB 創建數據庫的語法格式:use DATABASE_NAME
如果數據庫不存在,則創建數據庫,否則切換到指定數據庫。
實例
以下實例我們創建了數據庫 test
> use test1
switched to db test1
> db
test
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
可以看到,我們剛創建的數據庫 runoob 並不在數據庫的列表中, 要顯示它,我們需要向 runoob 數據庫插入一些數據。
> db.runoob.insert({"name":"菜鳥就是我"})
WriteResult({ "nInserted" : 1 })
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test1 0.000GB
MongoDB 中默認的數據庫為 test,如果你沒有創建新的數據庫,集合將存放在 test 數據庫中。
刪除數據庫
語法
MongoDB 刪除數據庫的語法格式:db.dropDatabase()
實例
以下實例我們刪除了數據庫 test1。
# 首先,查看所有數據庫
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
test1 0.000GB
# 切換到數據庫 test1
> use test1
switched to db test1
# 執行刪除命令
> db.dropDatabase()
{ "ok" : 1 }
# 查看數據庫 test1 是否還存在
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
>
集合操作
集合,類似關系型數據庫中的表。
可以顯式的創建,也可以隱式的創建。
查看集合
查看當前庫中的表/集合:show tables
或者 show collections
命令
> show collections
mycollection
> show tables
mycollection
>
創建集合
顯式創建集合
語法格式:db.createCollection(name)
參數說明:
- name - 要創建的集合名稱
舉例說明:創建一個名為 mycollection 的普通集合。
> db.createCollection("mycollection")
{ "ok" : 1 }
> show tables
mycollection
集合的命名規范參考:集合的命名規范
隱式創建集合
當向一個集合中插入一個文檔的是夠,如果集合不存在,則會自動創建集合。
具體請看:提示
通常我們使用隱式創建文檔即可。
刪除集合
語法格式: db.某個集體集合名.drop()
返回值:如果成功刪除選定集合,則 drop() 方法返回 true,否則返回 false。
示例:要刪除mycollection集合
> show tables
mycollection
> db.mycollection.drop()
true
> show tables
>
文檔操作
文檔(document)的數據結構和JSON基本一樣。
所有存儲在集合中的數據都是BSON格式。關於BSON的介紹可以查看:數據模型
查詢文檔
語法格式:db.collection.find(<query>, [projection])
參數說明:
Parameter | Type | Description |
query | document | 可選。使用查詢運算符指定選擇篩選器。若要返回集合中的所有文檔,請省略此參數或傳遞空文檔( {} )。 |
projection | document | 可選。指定要在與查詢篩選器匹配的文檔中返回的字段(投影)。若要返回匹配文檔中的所有字段,請省略此參數 |
實例1:查詢所有 db.comment.find()
或 db.comment.find({})
> db.comment.find()
{ "_id" : ObjectId("61bfc69ab5617497c0621b00"), ... }
{ "_id" : "1", "articleid" : "100001", ... }
{ "_id" : "2", "articleid" : "100001", ... }
{ "_id" : "3", "articleid" : "100001", ... }
{ "_id" : "4", "articleid" : "100001", ... }
{ "_id" : "5", "articleid" : "100001", ... }
> db.comment.find({})
{ "_id" : ObjectId("61bfc69ab5617497c0621b00"), ... }
{ "_id" : "1", "articleid" : "100001", ... }
{ "_id" : "2", "articleid" : "100001", ... }
{ "_id" : "3", "articleid" : "100001", ... }
{ "_id" : "4", "articleid" : "100001", ... }
{ "_id" : "5", "articleid" : "100001", ... }
# 按一定條件來查詢 只需要在find()中添加參數即可
> db.comment.find({userid:'1003'})
{ "_id" : "4", "articleid" : "100001", "userid" : "1003", ... }
{ "_id" : "5", "articleid" : "100001", "userid" : "1003", ... }
>
提示:每條文檔會有一個叫_id的字段,這個相當於我們原來關系數據庫中表的主鍵,當你在插入文檔記錄時沒有指定該字段,MongoDB會自動創建,其類型是ObjectID類型。
實例2:投影查詢(Projection Query):要查詢結果返回部分指定字段,則需要使用投影查詢
# 查詢結果只顯示 _id、userid、nickname
> db.comment.find({userid:"1003"},{userid:1,nickname:1})
{ "_id" : "4", "userid" : "1003", "nickname" : "凱 撒" }
{ "_id" : "5", "userid" : "1003", "nickname" : "凱撒" }
# 查詢結果只顯示 、userid、nickname ,不顯示 _id
> db.comment.find({userid:"1003"},{userid:1,nickname:1,_id:0})
{ "userid" : "1003", "nickname" : "凱 撒" }
{ "userid" : "1003", "nickname" : "凱撒" }
# 查詢所有數據,但只顯示 _id、userid、nickname
> db.comment.find({},{userid:1,nickname:1})
{ "_id" : ObjectId("61bfc69ab5617497c0621b00"), "userid" : "1001", "nickname" : "Rose" }
{ "_id" : "1", "userid" : "1002", "nickname" : "相忘於江湖" }
{ "_id" : "2", "userid" : "1005", "nickname" : "伊人憔 悴" }
{ "_id" : "3", "userid" : "1004", "nickname" : "傑克船 長" }
{ "_id" : "4", "userid" : "1003", "nickname" : "凱 撒" }
{ "_id" : "5", "userid" : "1003", "nickname" : "凱撒" }
>
插入文檔
插入單個文檔
使用 insert()
或 save()
方法向集合中插入文檔。
語法格式:db.collection.insert( <document or array of documents>, { writeConcern: <document>, ordered: <boolean> } )
參數說明:
Parameter | Type | Description |
document | document or array | 要插入到集合中的文檔或文檔數組。((json格式) |
writeConcern | document | Optional. A document expressing the write concern. Omit to use the default write concern.See Write Concern.Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern. |
ordered | boolean | 可選。如果為真,則按順序插入數組中的文檔,如果其中一個文檔出現錯誤,MongoDB將返回而不處理數組中的其余文檔。如果為假,則執行無序插入,如果其中一個文檔出現錯誤,則繼續處理數組中的主文檔。在版本2.6+中默認為true |
示例:向comment的集合(表)中插入一條測試數據
> db.comment.insert({"articleid":"100000","content":"今天天氣真好, 陽光明 媚","userid":"1001","nickname":"Rose","createdatetime":new Date(),"likenum":NumberInt(10),"state":null})
WriteResult({ "nInserted" : 1 })
>
提示
- comment集合如果不存在,則會隱式創建
- MongoDB中的數數字, 默認情況下是 double 類型,如果要存整型,必須使用函數
NumberInt(整型數字)
,否則取出來就有問題了。 - 插入當前日期使用
new Date()
- 插入的數據沒有指定
_id
, 會自動生成主鍵值 - 如果某字段沒值,可以賦值為
null
, 或不寫該字段
執行后,如下,說明插入一條數據成功了。
WriteResult({ "nInserted" : 1 })
注意
- 文檔中的鍵/值對是有序的。
- 文檔中的值不僅可以是在雙引號里面的字符串,還可以是其他幾種數據類型(甚至可以是整個嵌入的文檔)。
- MongoDB區分類型和大小寫
- MongoDB的文檔不能有重復的鍵。文檔的鍵是字符串。除了少數例外情況,鍵可以使用任意UTF-8字符。
文檔鍵命名規范請看:文檔的命名規范
批量插入文檔
語法格式:db.collection.insertMany( [ <document 1> , <document 2>, ... ], { writeConcern: <document>, ordered: <boolean> } )
參數說明
Parameter | Type | Description |
document | document or array | 要插入到集合中的文檔或文檔數組。((json格式) |
writeConcern | document | Optional. A document expressing the write concern. Omit to use the default write concern.See Write Concern.Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern. |
ordered | boolean | 可選。一個布爾值,指定Mongod實例應執行有序插入還是無序插入。默認為true。 |
實例:批量插入多條文章評論
> db.comment.insertMany([ {"_id":"1","articleid":"100001","content":"我們不應該把清晨浪費在手機上,健康很重要,一杯溫水幸福你我 他。","userid":"1002","nickname":"相忘於江湖","createdatetime":new Date("2019-08- 05T22:08:15.522Z"),"likenum":NumberInt(1000),"state":"1"}, {"_id":"2","articleid":"100001","content":"我夏天空腹喝涼開水,冬天喝溫開水","userid":"1005","nickname":"伊人憔 悴","createdatetime":new Date("2019-08-05T23:58:51.485Z"),"likenum":NumberInt(888),"state":"1"}, {"_id":"3","articleid":"100001","content":"我一直喝涼開水,冬天夏天都喝。","userid":"1004","nickname":"傑克船 長","createdatetime":new Date("2019-08-06T01:05:06.321Z"),"likenum":NumberInt(666),"state":"1"}, {"_id":"4","articleid":"100001","content":"專家說不能空腹吃飯,影響健康。","userid":"1003","nickname":"凱 撒","createdatetime":new Date("2019-08-06T08:18:35.288Z"),"likenum":NumberInt(2000),"state":"1"}, {"_id":"5","articleid":"100001","content":"研究表明,剛燒開的水千萬不能喝,因為燙 嘴。","userid":"1003","nickname":"凱撒","createdatetime":new Date("2019-08- 06T11:01:02.521Z"),"likenum":NumberInt(3000),"state":"1"} ]);
{
"acknowledged" : true,
"insertedIds" : [
"1",
"2",
"3",
"4",
"5"
]
}
提示
- 插入時指定了 _id ,則主鍵就是該值。
- 如果某條數據插入失敗,將會終止插入,但已經插入成功的數據不會回滾掉。
因為批量插入由於數據較多容易出現失敗,因此,可以使用try catch進行異常捕捉處理,測試的時候可以不處理。如(了解):
> try { db.comment.insertMany([ {"_id":"1","articleid":"100001","content":"我們不應該把清晨浪費在手機上,健康很重要,一杯溫水幸福你我 他。","userid":"1002","nickname":"相忘於江湖","createdatetime":new Date("2019-08- 05T22:08:15.522Z"),"likenum":NumberInt(1000),"state":"1"}, {"_id":"2","articleid":"100001","content":"我夏天空腹喝涼開水,冬天喝溫開水","userid":"1005","nickname":"伊人憔 悴","createdatetime":new Date("2019-08-05T23:58:51.485Z"),"likenum":NumberInt(888),"state":"1"}, {"_id":"3","articleid":"100001","content":"我一直喝涼開水,冬天夏天都喝。","userid":"1004","nickname":"傑克船 長","createdatetime":new Date("2019-08-06T01:05:06.321Z"),"likenum":NumberInt(666),"state":"1"}, {"_id":"4","articleid":"100001","content":"專家說不能空腹吃飯,影響健康。","userid":"1003","nickname":"凱 撒","createdatetime":new Date("2019-08-06T08:18:35.288Z"),"likenum":NumberInt(2000),"state":"1"}, {"_id":"5","articleid":"100001","content":"研究表明,剛燒開的水千萬不能喝,因為燙 嘴。","userid":"1003","nickname":"凱撒","createdatetime":new Date("2019-08- 06T11:01:02.521Z"),"likenum":NumberInt(3000),"state":"1"} ]); } catch (e) { print (e); }
BulkWriteError({
"writeErrors" : [
{
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test1.comment index: _id_ dup key: { _id: \"1\" }",
"op" : {
"_id" : "1",
"articleid" : "100001",
"content" : "我們不應該把清晨浪費在手機上,健康很重要,一杯溫水幸福你我 他。",
"userid" : "1002",
"nickname" : "相忘於江湖",
"createdatetime" : ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ"),
"likenum" : NumberInt(1000),
"state" : "1"
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
>
更新文檔
語法格式: db.collection.update(query, update, options)
或者 db.collection.update( <query>, <update>, { upsert: <boolean>, multi: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [ <filterdocument1>, ... ], hint: <document|string> // Available starting in MongoDB 4.2 } )
參數
提示:主要關注前四個參數即可
實例
# 覆蓋修改,將刪除執行語句中未指定的其他的字段
> db.comment.update({_id:"1"},{likenum:NumberInt(1001)})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.comment.find({_id:"1"})
{ "_id" : "1", "likenum" : 1001 }
>
# 局部修改,為了解決上面的問題,我們需要使用修改器$set來實現
> db.comment.update({_id:"2"},{$set:{likenum:NumberInt(889)}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.comment.find({_id:"2"})
{ "_id" : "2", "articleid" : "100001", ... }
>
# 批量修改 更新用戶為 1003 的用戶的昵稱為 凱撒大帝
## 默認只更新第一條數據
> db.comment.update({userid:"1003"},{$set:{nickname:"凱撒2"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.comment.find({userid:"1003"})
{ "_id" : "4", "articleid" : "100001", "nickname" : "凱撒2", ... }
{ "_id" : "5", "articleid" : "100001", "nickname" : "凱撒", ... }
>
## 修改所有符合條件的數據,需要指定參數 {multi:true}
> db.comment.update({userid:"1003"},{$set:{nickname:"凱撒大帝"}},{multi:true})
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
> db.comment.find({userid:"1003"})
{ "_id" : "4", "articleid" : "100001", "nickname" : "凱撒大帝", ... }
{ "_id" : "5", "articleid" : "100001", "nickname" : "凱撒大帝", ... }
>
# 列值增長的修改:如果我們想實現對某列值在原有值的基礎上進行增加或減少,可以使用 $inc 運算符來實現。
## 對3號數據的點贊數,每次遞增1
> db.comment.find({_id:"3"})
{ "_id" : "3", "likenum" : 667, ... }
> db.comment.update({_id:"3"},{$inc:{likenum:NumberInt(1)}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.comment.find({_id:"3"})
{ "_id" : "3", "likenum" : 668, ... }
>
刪除文檔
語法格式:db.集合名稱.remove(條件)
實例
# 刪除_id=1的記錄
> db.comment.remove({_id:"1"})
WriteResult({ "nRemoved" : 1 })
> db.comment.find({_id:"1"})
>
# 可以將數據全部刪除,請慎用
> db.comment.find({})
{ "_id" : ObjectId("61bfc69ab5617497c0621b00"), "articleid" : "100000", ... }
{ "_id" : "2", "articleid" : "100001", ... }
{ "_id" : "3", "articleid" : "100001", ... }
{ "_id" : "4", "articleid" : "100001", ... }
{ "_id" : "5", "articleid" : "100001", ... }
> db.comment.remove({})
WriteResult({ "nRemoved" : 5 })
> db.comment.find({})
>
更多查詢方式
上面介紹了關於文檔的一些基本查詢,我們接着學習一些關於查詢的使用方式。
統計查詢
統計查詢使用 count()
方法。
語法格式:db.collection.count(query, options)
參數說明:
Parameter | Type | Description |
query | document | 查詢選擇條件。 |
options | document | 可選。用於修改計數的額外選項。 |
實例
# 統計所有記錄數
> db.comment.count()
5
>
# 按條件統計:統計userid為1003的記錄條數
> db.comment.count({userid:"1003"})
2
>
分頁列表查詢
可以使用limit()
方法來讀取指定數量的數據,使用skip()
方法來跳過指定數量的數據。
語法格式:db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
實例
# 返回指定條數的記錄:調用limit來返回結果(TopN),默認值20
> db.comment.find().limit(3)
{ "_id" : "1", "articleid" : "100001", ... }
{ "_id" : "2", "articleid" : "100001", ... }
{ "_id" : "3", "articleid" : "100001", ... }
>
# skip方法同樣接受一個數字參數作為跳過的記錄條數。(前N個不要),默認值是0
> db.comment.count()
5
> db.comment.find().skip(3)
{ "_id" : "4", "articleid" : "100001", ...}
{ "_id" : "5", "articleid" : "100001", ...}
>
# 分頁查詢:每頁2個,第二頁開始:跳過前兩條數據,接着值顯示3和4條數據
> db.comment.find().skip(0).limit(2)
{ "_id" : "1", "articleid" : "100001", ....}
{ "_id" : "2", "articleid" : "100001", ....}
> db.comment.find().skip(2).limit(2)
{ "_id" : "3", "articleid" : "100001", ....}
{ "_id" : "4", "articleid" : "100001", ....}
> db.comment.find().skip(4).limit(2)
{ "_id" : "5", "articleid" : "100001", ....}
>
排序查詢
sort()
方法對數據進行排序,sort() 方法可以通過參數指定排序的字段,並使用 1 和 -1 來指定排序的方式,其中 1 為升序排列,而 -1 是用於降序排列。
語法格式:db.COLLECTION_NAME.find().sort({KEY:1})
實例
# 對userid和訪問量進行排列
> db.comment.find().sort({userid:-1,likenum:1})
{ "_id" : "2", "userid" : "1005", "likenum" : 888, ...}
{ "_id" : "3", "userid" : "1004", "likenum" : 666, ...}
{ "_id" : "4", "userid" : "1003", "likenum" : 2000, ...}
{ "_id" : "5", "userid" : "1003", "likenum" : 3000, ...}
{ "_id" : "1", "userid" : "1002", "likenum" : 1000, ...}
> db.comment.find().sort({likenum:1})
{ "_id" : "3", "userid" : "1004", "likenum" : 666, ...}
{ "_id" : "2", "userid" : "1005", "likenum" : 888, ...}
{ "_id" : "1", "userid" : "1002", "likenum" : 1000, ...}
{ "_id" : "4", "userid" : "1003", "likenum" : 2000, ...}
{ "_id" : "5", "userid" : "1003", "likenum" : 3000, ...}
> db.comment.find().sort({userid:-1,likenum:-1})
{ "_id" : "2", "userid" : "1005", "likenum" : 888, ...}
{ "_id" : "3", "userid" : "1004", "likenum" : 666, ...}
{ "_id" : "5", "userid" : "1003", "likenum" : 3000, ...}
{ "_id" : "4", "userid" : "1003", "likenum" : 2000, ...}
{ "_id" : "1", "userid" : "1002", "likenum" : 1000, ...}
>
提示:skip()
, limilt()
, sort()
三個放在一起執行的時候,執行的順序是先 sort()
, 然后是 skip()
,最后是顯示的 limit()
,和命令編寫順序無關。
正則條件查詢
MongoDB的模糊查詢是通過正則表達式的方式實現的。
語法格式:db.集合.find({字段:/正則表達式/})
提示:正則表達式是js的語法,直接量的寫法。
實例
# 查詢評論內容包含“開水”的所有文檔
> db.comment.find({content:/開水/})
{ "_id" : "2", "articleid" : "100001", "content" : "我夏天空腹喝涼開水,冬天喝溫開水", ... }
{ "_id" : "3", "articleid" : "100001", "content" : "我一直喝涼開水,冬天夏天都喝。", ... }
# 查詢評論的內容中以“專家”開頭的
> db.comment.find({content:/^專家/})
{ "_id" : "4", "articleid" : "100001", "content" : "專家說不能空腹吃飯,影響健康。", ... }
>
比較查詢
<, <=, >, >= 這個操作符也是很常用的。
語法格式
db.集合名稱.find({ "field" : { $gt: value }}) // 大於: field > value
db.集合名稱.find({ "field" : { $lt: value }}) // 小於: field < value
db.集合名稱.find({ "field" : { $gte: value }}) // 大於等於: field >= value
db.集合名稱.find({ "field" : { $lte: value }}) // 小於等於: field <= value
db.集合名稱.find({ "field" : { $ne: value }}) // 不等於: field != value
實例
# 查詢評論點贊數量大於700的記錄
> db.comment.find({likenum:{$gt:NumberInt(700)}})
{ "_id" : "1", "articleid" : "100001", ... , "likenum" : 1000, "state" : "1" }
{ "_id" : "2", "articleid" : "100001", ... , "likenum" : 888, "state" : "1" }
{ "_id" : "4", "articleid" : "100001", ... , "likenum" : 2000, "state" : "1" }
{ "_id" : "5", "articleid" : "100001", ... , "likenum" : 3000, "state" : "1" }
>
條件連接查詢
我們如果需要查詢同時滿足兩個以上條件,需要使用$and
操作符將條件進行關聯。(相 當於SQL的and)
如果兩個以上條件之間是或者的關系,我們使用 $or
操作符進行關聯
語法格式:$and:[ { },{ },{ } ]
、$or:[ { },{ },{ } ]
實例
# 查詢評論集合中likenum大於等於700 並且小於2000的文檔
> db.comment.find({$and:[{likenum:{$gte:NumberInt(700)}},{likenum:{$lt:NumberInt(2000)}}]})
{ "_id" : "1", "articleid" : "100001", ... , "likenum" : 1000, "state" : "1" }
{ "_id" : "2", "articleid" : "100001", ... , "likenum" : 888, "state" : "1" }
# 查詢評論集合中userid為1003,或者點贊數小於1000的文檔記錄
> db.comment.find({$or:[ {userid:"1003"} ,{likenum:{$lt:1000} }]})
{ "_id" : "2", ... , "userid" : "1005", "likenum" : 888, "state" : "1" }
{ "_id" : "3", ... , "userid" : "1004", "likenum" : 666, "state" : "1" }
{ "_id" : "4", ... , "userid" : "1003", "likenum" : 2000, "state" : "1" }
{ "_id" : "5", ... , "userid" : "1003", "likenum" : 3000, "state" : "1" }
>
美文佳句
《牛津格言》里曾經講過一段話,讓我印象很深刻:“如果我們僅僅想獲得快樂,那很容易實現。但我們希望比別人更快樂,就會感到難以實現。因為我們對於別人快樂的想象,總是超過實際情形。”
我們常常埋怨生活有太多的不如意,總覺得自己的際遇不如別人。 但其實,人最大的不如意,是不懂知足。