標籤:
安裝mongodb
sudo apt-get install mongodb
... ...
設定用戶端串連
開啟檔案/etc/mongodb.conf 注意許可權
修改 bind_ip=127.0.0.1 為 bind_ip=0.0.0.0
設定串連使用者名稱和密碼及常用命令
進入mongodb互動模式
>mongo
建立串連使用者
>use admin
>db.addUser(‘username‘,‘password‘)
使用者驗證
>db.auth(‘username‘,‘password‘)
查看資料集
>db.collections
... ...
查看使用者列表
>db.system.users.find()
查看所有使用者
>show user
刪除使用者
>db.removeUser(‘username‘)
查看所有資料庫
>show dbs
查看資料集狀態
>db.printCollectionStats()
查看資料庫介紹
>show profile
刪除資料集
>db.demo_col.drop()
刪除當前資料庫
>db.dropDatabase()
服務啟動與關閉
sudo service mongodb start
sudo service mongodb stop
增刪改查 [資料庫名稱demoDB]
添加資料
>db.demoDB.save({‘name‘:‘bob‘,‘email‘:[‘[email protected]‘,‘[email protected]‘],‘sex‘:1})
修改資料
格式:db.collection.update( criteria, objNew, upsert, multi )
criteria : update的查詢條件,類似sql update查詢內where後面的
objNew : update的對象和一些更新的操作符(如$,$inc...)等,也可以理解為sql update查詢內set後面的
upsert : 這個參數的意思是,如果不存在update的記錄,是否插入objNew,true為插入,預設是false,不插入。
multi : mongodb預設是false,只更新找到的第一條記錄,如果這個參數為true,就把按條件查出來多條記錄全部更新。
>db.demoDB.update({‘name‘:‘bob‘},{‘$set‘:{‘sex‘:0},upsert=true,multi=true})
刪除資料
>db.demoDB.remove({‘name‘:‘bob‘})
刪除所有記錄
>db.demoDB.remove()
查詢所有資料
>db.demoDB.find()
查詢最上面一條資料
>db.demoDB.findOne()
根據條件查詢指定條數的資料
>db.demoDB.find({‘sex‘:0}).limit(2)
跳過指定條數
>db.demoDB.skip(10)
排序sort
>db.demoDB.find({‘sex‘:0}).sort({‘name‘:-1})
計數操作
>db.demoDB.find({‘sex‘:0}).count()
>db.demoDB.count()
查詢指定列,去除重複
>db.demoDB.distinct(‘sex‘)
子物件尋找
>db.demoDB.distinct({‘addr.province‘:‘beijing‘})
條件操作符尋找
gt:大於
lt:小於
gte:大於等於
lte:小於等於
ne:不等於
in:in包含 $in:[1,2,3,4]
type:數實值型別 [double 1 , string 2 ,object 3,array 4, binary data 5,object id 7 ,boolean 8,date 9,null 10,reg 11,js code 13 ,32-bit integer 16 ,timestamp 17,64-bit integer 18,]
exist:是否存在 $exist:false/true
where:js查詢 $where:‘this.sex=0‘
>db.demoDB.find({‘sex‘:{$in:[0,1]}})
模糊查詢--使用Regex
>db.demoDB.find({name:/^b.*/i})
ubuntu系統安裝mongodb