南昌做網(wǎng)站今日要聞
目錄
一、數(shù)據(jù)庫(kù)操作
1、創(chuàng)建數(shù)據(jù)庫(kù)操作
2、查看當(dāng)前有哪些數(shù)據(jù)庫(kù)
3、查看當(dāng)前在使用哪個(gè)數(shù)據(jù)庫(kù)
4、刪除數(shù)據(jù)庫(kù)
二、集合操作
1、查看有哪些集合
2、刪除集合
3、創(chuàng)建集合
三、文檔基本操作
1、插入數(shù)據(jù)
2、查詢數(shù)據(jù)
3、刪除數(shù)據(jù)
4、修改數(shù)據(jù)
四、文檔分頁(yè)查詢
五、文檔其他查詢
1、正則條件查詢(模糊查詢)
2、比較查詢
3、包含查詢(in)
4、條件查詢
一、數(shù)據(jù)庫(kù)操作
1、創(chuàng)建數(shù)據(jù)庫(kù)操作
use 數(shù)據(jù)庫(kù)名? # 如果該數(shù)據(jù)庫(kù)存在,則該命令變?yōu)槭褂迷摂?shù)據(jù)庫(kù)
2、查看當(dāng)前有哪些數(shù)據(jù)庫(kù)
show dbs? # 也可以使用show databases進(jìn)行查看
3、查看當(dāng)前在使用哪個(gè)數(shù)據(jù)庫(kù)
db?
4、刪除數(shù)據(jù)庫(kù)
db.dropDatabase()? # 將當(dāng)前數(shù)據(jù)庫(kù)刪除
二、集合操作
1、查看有哪些集合
show collections
2、刪除集合
db.name.dropCollection()? # 將名為name的集合刪除
3、創(chuàng)建集合
集合的創(chuàng)建有兩種方式:顯示創(chuàng)建、隱式創(chuàng)建,其中隱式創(chuàng)建是在進(jìn)行文檔插入時(shí)自動(dòng)創(chuàng)建出的集合,在下文提及,這里先學(xué)習(xí)顯示創(chuàng)建
db.createCollection(name)? ?# 創(chuàng)建出一個(gè)名為name的集合
三、文檔基本操作
1、插入數(shù)據(jù)
db.collection.insert(data)
#? 將數(shù)據(jù)插入collection中此處的collection是具體的集合名稱,如果該集合不存在于數(shù)據(jù)庫(kù),則會(huì)隱式的創(chuàng)建出該集合并將數(shù)據(jù)插入
db.collection.insertMany([{數(shù)據(jù)1},{數(shù)據(jù)2}])? # 將多個(gè)數(shù)據(jù)插入
示例:db.person.insert({"username":"zs","age":"10"})
2、查詢數(shù)據(jù)
db.collection.find()? # 將數(shù)據(jù)全部查詢
db.collection.find({username:"zs"})? # 根據(jù)條件進(jìn)行查詢
?db.collection.find({username:"zs"},{username:1,_id:0}) # 投影查詢,其中1表示顯示字段,0表示不顯示該字段
3、刪除數(shù)據(jù)
db.collection.remove({})? # 全部刪除
db.collection.remove({_id:"111"}) # 將id為111的數(shù)據(jù)刪除
4、修改數(shù)據(jù)
db.collection.update({userid:"1"},{username:"zs"})? # 覆蓋修改,將userid為1的數(shù)據(jù)修改為username:"zs"},這種修改方式會(huì)導(dǎo)致其他字段消失,僅留下第二個(gè)參數(shù)的數(shù)據(jù)
db.collection.update({userid:"1"},{$set:{username:"zs"}})? # 這種修改會(huì)將userid為1的第一條數(shù)據(jù)中的username這一個(gè)字段修改為zs,其余字段不會(huì)被刪除
db.collection.update({userid:"1"},{username:"zs"},{multi:true}) # 這種修改會(huì)將userid為1的所有數(shù)據(jù)的username進(jìn)行修改
db.collection.update({userid:"1"},{$inc:{count:NumberInt(1)}})? # 會(huì)將userid為1的用戶的count字段自增1
四、文檔分頁(yè)查詢
db.collection.count(條件)# 統(tǒng)計(jì)該集合中的數(shù)據(jù)條數(shù),如果不加條件則是全部數(shù)據(jù)的條數(shù)
db.collection.find(條件).skip(數(shù)值m).limit(數(shù)值n) # 指的是查詢符合條件的數(shù)據(jù)中跳過(guò)m條后取n條數(shù)據(jù)返回
db.collection.find(條件).sort({userid:1,id:-1}) # 其中1指的是按照userid升序 -1指的是按照id降序
?
五、文檔其他查詢
1、正則條件查詢(模糊查詢)
db.collection.find({username:/ss/})? ?# 查詢集合里username中包含ss的數(shù)據(jù)
db.collection.find({username:/^張/})? # 查詢集合里username以張開(kāi)頭的數(shù)據(jù)
2、比較查詢
db.collection.find({count:{$gt:NumberInt(30)})? # 查詢集合中count字段值大于30的數(shù)據(jù)
< :? $lt
<= : $lte?
> : $ gt
>= :$gte
!=? : $ne
3、包含查詢(in)
db.collection.find({count:{$in:[11,12]}})? # 查詢集合里count是11,12的數(shù)據(jù)
如果是排除11與12則使用$nin?
4、條件查詢
db.collection.find({$and[{條件1},{條件2}]})
db.collection.find({$or[{條件1},{條件2}]})