本文轉載自菜鳥教程的mongodb教程
MongoDB 概念解析
SQL術語/概念 | MongoDB術語/概念 | 解釋/說明 |
---|---|---|
database | database | 數據庫 |
table | collection | 數據庫表/集合 |
row | document | 數據記錄行/文檔 |
column | field | 數據字段/域 |
index | index | 索引 |
table joins | 表連接,MongoDB不支持 | |
primary key | primary key | 主鍵,MongoDB自動將_id字段設置爲主鍵 |
連接
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
MongoDB 創建數據庫
#創建數據庫
use mydb
#查看所有數據庫
show dbs
注意:新創建的數據庫要插入文檔纔會顯示
刪除數據庫
#切換到數據庫
use mydb
#刪除數據庫
db.dropDatabase()
創建集合
# mycol爲集合名字
db.createCollection(mycol)
# 另一種方法是,在插入文檔的時候,會自動創建集合
db.mycol.insert({name:"李雷"})
#查看集合
show collections
刪除集合
#collectionname爲要刪除的集合名
db.collectionname.drop()
插入文檔
db.COLLECTION_NAME.insert(document)
更新文檔
update()方法
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
- query : update的查詢條件,類似sql update查詢內where後面的。
- update : update的對象和一些更新的操作符(如$set,$inc...)等,也可以理解爲sql update查詢內set後面的
- upsert : 可選,這個參數的意思是,如果不存在update的記錄,是否插入objNew,true爲插入,默認是false,不插入。
- multi : 可選,mongodb 默認是false,只更新找到的第一條記錄,如果這個參數爲true,就把按條件查出來多條記錄全部更新。
- writeConcern :可選,拋出異常的級別。
> use mydb switched to db mydb > db.student.insert({name:"李雷"}) WriteResult({ "nInserted" : 1 }) > db.student.update({name:"李雷"},{$set:{name:"韓梅梅"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.student.find() { "_id" : ObjectId("5bb088934c5c8e8a18b5c1c0"), "name" : "韓梅梅" }
save()方法
刪除文檔
deleteOne()方法和deleteMany()方法
> db.student.deleteOne({name:"李雷"}) { "acknowledged" : true, "deletedCount" : 1 } # 刪除集合中所有文檔 > db.student.deleteMany({}) { "acknowledged" : true, "deletedCount" : 1 }
查詢文檔
find()方法
操作 | 格式 | 範例 | RDBMS中的類似語句 |
---|---|---|---|
等於 | {<key>:<value>} | db.col.find({"by":"菜鳥教程"}).pretty() | where by = '菜鳥教程' |
小於 | {<key>:{$lt:<value>}} | db.col.find({"likes":{$lt:50}}).pretty() | where likes < 50 |
小於或等於 | {<key>:{$lte:<value>}} | db.col.find({"likes":{$lte:50}}).pretty() | where likes <= 50 |
大於 | {<key>:{$gt:<value>}} | db.col.find({"likes":{$gt:50}}).pretty() | where likes > 50 |
大於或等於 | {<key>:{$gte:<value>}} | db.col.find({"likes":{$gte:50}}).pretty() | where likes >= 50 |
不等於 | {<key>:{$ne:<value>}} | db.col.find({"likes":{$ne:50}}).pretty() | where likes != 50 |
條件
and
# db.COLLECTION_NAME.find(<query1>,<query2>...)
or
# db.COLLECTION_NAME.find($or:[<query1>,<query2>...])
-
$gt -------- greater than >
-
$gte --------- gt equal >=
-
$lt -------- less than <
-
$lte --------- lt equal <=
-
$ne ----------- not equal !=
- $eq -------- equal =
Limit與Skip方法
# NUM1, 讀取指定數量的數據
# NUM2, 跳過的記錄條數
db.COLLECTION_NAME.find({}).skip(NUM1).limit(NUM2)
排序
sort()方法
1爲升序,-1爲降序
db.COLLECTION_NAME.find().sort({KEY:1})