MongoDb基礎命令

一些基礎忘記隨時查看。。

#整備恢復

mongodump --port 20001 --authenticationDatabase=admin -u *  -d lvlv -c lvlv -o /home

mongorestore --drop  --host 172.16.201.74  --port 20001 --authenticationDatabase=admin -umgbackup -d test /tmp/liding/test/liding.bson


#基於時間備份oplog

mongodump --port 20001  --authenticationDatabase=admin -u* -d local -c oplog.rs -q 'ts:{$lt:Timestamp(1462830369,1),$gt: Timestamp(1462821613, 1)}}' -o /tmp/lidddd


#將oplog恢復到臨時庫

mongorestore -u* --authenticationDatabase=admin --host 172.16.201.73 --port 27017 -d local -c oplog.rs  /data/backup/oplog1/local/oplog.rs.bson

 

#從臨時庫重放oplog  

mongooplog --port 20001 -u* --authenticationDatabase=admin --from=172.16.201.73:27017 



oplog查找

db.oplog.rs.find({ts:{$lt:Timestamp(1462917498, 1),$gt:Timestamp(1462918425, 1)}}).pretty()



use local 

 db.oplog.rs.find()

date -d @1361542596 +"%Y-%m-%d %H:%M:%S"

 for (var i=0;i<1000;i++){db.lvlv.save({"xywy":i})}

 

 

 sql="db.getReplicationInfo();"

echo "$sql"|/usr/local/xywy/mongodb-3.0.8/bin/mongo  127.0.0.1:20001/admin -u* -pC^8cE#1RvX5rBg0 --authenticationDatabase=admin --shell


添加管理用戶:

 

use admin

db.createUser(

  {

    user: "*",

    pwd: "*****",

    roles: [ { role: "root", db: "admin" } ]

  }

)

 

添加備份用戶:

use admin

db.createUser(

  {

    user: "mgbackup",

    pwd: "*********",

    roles: [ { role: "backup", db: "admin" }, { role: "restore", db: "admin" } ]

  }

)

添加日常操作用戶:

use admin

db.createUser(

  {

    user: "mgadmin",

    pwd: "*****",

    roles: [ { role: "readWriteAnyDatabase", db:admin } ]

  }

)

 

 

添加讀寫用戶:

 

use admin

db.createUser(

 {

   user: "liuyunsong",

   pwd: "*****",

   roles: [

      { role: "rw", db: "123" }

   ]

 }

)

 

修改用戶權限:

use admin

db.runCommand(

  {

    updateUser:"liuyaxin",

    pwd:"****",

         roles: [

    { role: "read", db: "123" }

         ]

  }

)

 

刪除用戶:

use 123

db.dropUser("123")

 

刪除一個庫下所有用戶:

use 123

db. dropAllUsers ()

 

對用戶添加角色:

use 123

db.runCommand( { grantRolesToUser: "*",

                 roles: [

                    { role: "admin", db: "admin"}

                 ]

             } )

 

對用戶移除角色:

use 123

db.runCommand( { revokeRolesFromUser: "liuyaxin",

                 roles: [

                    { role: "read", db: "234"}

                 ]

             } )

創建角色:

use admin

db.runCommand({ createRole: "rw",

  privileges: [

    { resource: { db: "123", collection: "" }, actions: [ "find", "update", "insert", "remove" ] }

  ],

  roles: [

    { role: "read", db: "admin" }

  ]

})

修改角色權限:

use admin

db.runCommand(

   {

     updateRole: "rw",

     privileges:

         [

           {

             resource: { db: "123", collection: "" },

             actions: [ "find" , "update", "insert", "remove" ]

           }

         ],

     roles:

         [

           { role: "read", db: "admin" }

         ]

   }

)

 

刪除角色:

use admin

db.runCommand(

   {

     dropRole: "rw",

     writeConcern: { w: "majority" }

   }

)

刪除所有角色:

Use 123

db.runCommand(

   {

     dropAllRolesFromDatabase: 1,

     writeConcern: { w: "majority" }

   }

)

爲角色增加權限:

use 123

db.runCommand(

   {

     grantPrivilegesToRole: "rw",

     privileges: [

         {

           resource: { db: "123", collection: "" }, actions: [ "find" ]

         }

     ]

   }

)

移除角色權限:

Use 123

db.runCommand(

   {

     revokePrivilegesFromRole: "rw",

     privileges:

      [

        {

          resource: { db: "123", collection: "" },

          actions: [ "insert", "find" ]

        }

      ]

   }

)

刷新權限:

Use admin

db.runCommand( { invalidateUserCache: 1 } )


1、數據庫中查詢業務人員給的賬號在數據庫中是否存在

use database

show users

2、根據業務開發人員提出的需求授權

讀寫用戶名:庫名

先定義讀寫角色

use 庫名

db.runCommand({ createRole: "rw",

privileges: [

{ resource: { db: "庫名", collection: "" }, actions: [ "find", "update", "insert", "remove","listCollections"] }

],

roles: [

]

})

再加用戶

use 庫名

db.createUser(

{

user: "庫名",

pwd: "*****",

roles: [

{ role: "rw", db: "庫名" }

]

}

)


只讀用戶:庫名_r

先定義只讀角色

use 庫名

db.runCommand({ createRole: "r",

privileges: [

{ resource: { db: "庫名", collection: "" }, actions: [ "find","listCollections" ] }

],

roles: [

]

})

在添加用戶

use 庫名

db.createUser(

{

user: "庫名_r",

pwd: "************",

roles: [

{ role: "r", db: "庫名" }

]

}

)



3、檢驗授權有無生效 

使用授權的用戶登錄數據庫,查看該庫權限是否正確

use 庫名

db.auth("""")

4、將授權好的用戶名密碼發給該項目負責人同時發給dba組存檔,格式如下

idc:xx 主庫 ip:port 從庫 ip:port  

數據庫: databases 

讀寫用戶: databases 讀寫密碼: xxx

只讀用戶: databases_r 只讀密碼: xxx

管理用戶: database_admin 管理密碼: xxx


->use Admin         (切換到創建用戶)


->db.TestDb          (創建數據庫)


->db.addUser(“userName”,”Pwd”)    創建用戶


->db.auth(“userName”,”Pwd”)       設置用戶爲允許連接的用戶


->db.createCollection(“TableName”)                                     創建表


->showcollections                          查看錶是否創建成功


->db.TableName.Save({age:1})                 添加數據


->db.TableName.find()                        查看添加的數據是否成功(如果沒有查詢到任何的結果,說明添加失敗)


創建數據庫

語法

MongoDB 創建數據庫的語法格式如下:

use DATABASE_NAME

注:該命令只是在內存中臨時創建數據庫,創建後如果沒有寫入操作退出後會在內存中釋放

刪除數據庫

語法

MongoDB 刪除數據庫的語法格式如下:

db.dropDatabase()

注:刪除庫之前一定要先use database


插入文檔

MongoDB 使用 insert() 或 save() 方法向集合中插入文檔,語法如下:

db.COLLECTION_NAME.insert({document})

MongoDB 更新文檔

MongoDB 使用 update() 和 save() 方法來更新集合中的文檔。接下來讓我們詳細來看下兩個函數的應用及其區別。

update() 方法

update() 方法用於更新已存在的文檔。語法格式如下:

db.collection.update( <query>, <update>, { upsert: <boolean>, multi: <boolean>, writeConcern: <document> } )

參數說明:

query : update的查詢條件,類似sql update查詢內where後面的。

update : update的對象和一些更新的操作符(如$,$inc...)等,也可以理解爲sql update查詢內set後面的

upsert : 可選,這個參數的意思是,如果不存在update的記錄,是否插入objNew,true爲插入,默認是false,不插入。

multi : 可選,mongodb 默認是false,只更新找到的第一條記錄,如果這個參數爲true,就把按條件查出來多條記錄全部更新。

writeConcern :可選,拋出異常的級別。

save() 方法

save() 方法通過傳入的文檔來替換已有文檔。語法格式如下:

db.collection.save( <document>, { writeConcern: <document> } )

MongoDB 刪除文檔

MongoDB remove()函數是用來移除集合中的數據。

在執行remove()函數前先執行find()命令來判斷執行的條件是否正確,這是一個比較好的習慣。

語法

remove() 方法的基本語法格式如下所示:

db.collection.remove( <query>, { justOne: <boolean>, writeConcern: <document> } )

參數說明:

query :(可選)刪除的文檔的條件。

justOne : (可選)如果設爲 true 或 1,則只刪除一個文檔。

writeConcern :(可選)拋出異常的級別。

查詢文檔

語法

MongoDB 查詢數據的語法格式如下:

>db.COLLECTION_NAME.find()

find() 方法以非結構化的方式來顯示所有文檔。

如果你需要以易讀的方式來讀取數據,可以使用 pretty() 方法,語法格式如下:

>db.col.find().pretty()

MongoDB 與 RDBMS Where 語句比較

如果你熟悉常規的 SQL 數據,通過下表可以更好的理解 MongoDB 的條件語句查詢:

等於 {<key>:<value>} db.col.find({"by":"xywydba"}).pretty() where by = 'xywydba'

小於 {<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

操作

格式

範例

RDBMS中的類似語句

MongoDB AND 條件

MongoDB 的 find() 方法可以傳入多個鍵(key),每個鍵(key)以逗號隔開,及常規 SQL 的 AND 條件。

語法格式如下:

>db.col.find({key1:value1, key2:value2}).pretty()

 

MongoDB OR 條件

 

MongoDB OR 條件語句使用了關鍵字 $or,語法格式如下:

 

>db.col.find( { $or: [ {key1: value1}, {key2:value2} ] } ).pretty()

 

MongoDB Limit與Skip方法

MongoDB Limit() 方法

如果你需要在MongoDB中讀取指定數量的數據記錄,可以使用MongoDB的Limit方法,limit()方法接受一個數字參數,該參數指定從MongoDB中讀取的記錄條數。

語法

limit()方法基本語法如下所示:

>db.COLLECTION_NAME.find().limit(NUMBER)

MongoDB Skip() 方法

我們除了可以使用limit()方法來讀取指定數量的數據外,還可以使用skip()方法來跳過指定數量的數據,skip方法同樣接受一個數字參數作爲跳過的記錄條數。

語法

skip() 方法腳本語法格式如下:

>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)


MongoDB 排序

MongoDB sort()方法

在MongoDB中使用使用sort()方法對數據進行排序,sort()方法可以通過參數指定排序的字段,並使用 1 和 -1 來指定排序的方式,其中 1 爲升序排列,而-1是用於降序排列。

語法

sort()方法基本語法如下所示:

>db.COLLECTION_NAME.find().sort({KEY:1})

 

MongoDB 聚合

MongoDB中聚合(aggregate)主要用於處理數據(諸如統計平均值,求和等),並返回計算後的數據結果。有點類似sql語句中的 count(*)。

aggregate() 方法

MongoDB中聚合的方法使用aggregate()。

語法

aggregate() 方法的基本語法格式如下所示:

>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

下表展示了一些聚合的表達式:

表達式

描述

實例

$sum 計算總和。 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])

$avg 計算平均值 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}])

$min 獲取集合中所有文檔對應值得最小值。 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$likes"}}}])

$max 獲取集合中所有文檔對應值得最大值。 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$likes"}}}])

$push 在結果文檔中插入值到一個數組中。 db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])

$addToSet 在結果文檔中插入值到一個數組中,但不創建副本。 db.mycol.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}])

$first 根據資源文檔的排序獲取第一個文檔數據。 db.mycol.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}])

$last 根據資源文檔的排序獲取最後一個文檔數據 db.mycol.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])

管道的概念

管道在Unix和Linux中一般用於將當前命令的輸出結果作爲下一個命令的參數。

MongoDB的聚合管道將MongoDB文檔在一個管道處理完畢後將結果傳遞給下一個管道處理。管道操作是可以重複的。

表達式:處理輸入文檔並輸出。表達式是無狀態的,只能用於計算當前聚合管道的文檔,不能處理其它的文檔。

這裏我們介紹一下聚合框架中常用的幾個操作:

$project:修改輸入文檔的結構。可以用來重命名、增加或刪除域,也可以用於創建計算結果以及嵌套文檔。

$match:用於過濾數據,只輸出符合條件的文檔。$match使用MongoDB的標準查詢操作。

$limit:用來限制MongoDB聚合管道返回的文檔數。

$skip:在聚合管道中跳過指定數量的文檔,並返回餘下的文檔。

$unwind:將文檔中的某一個數組類型字段拆分成多條,每條包含數組中的一個值。

$group:將集合中的文檔分組,可用於統計結果。

$sort:將輸入文檔排序後輸出。

$geoNear:輸出接近某一地理位置的有序文檔。

管道操作符實例

1.$project實例

 

db.article.aggregate( { $project : { title : 1 , author : 1 , }} );

 

2.$match實例

 

db.articles.aggregate( [ { $match : { score : { $gt : 70, $lte : 90 } } }, { $group: { _id: null, count: { $sum: 1 } } } ] );

3.$skip實例

db.article.aggregate( { $skip : 5 });

mongoDB常用命令

1、與Mql對照

MySQL

MongoDB

說明

mysqld

mongod

服務器守護進程

mysql

mongo

客戶端工具

mysqldump

mongodump

邏輯備份工具

mysql

mongorestore

邏輯恢復工具

 

db.repairDatabase()

修復數據庫

mysqldump

mongoexport

數據導出工具

source

mongoimport

數據導入工具

grant * privileges on *.* to …

Db.addUser()

Db.auth()

新建用戶並權限

show databases

show dbs

顯示庫列表

Show tables

Show collections

顯示錶列表

Show slave status

Rs.status

查詢主從狀態

Create table users(a int, b int)

db.createCollection("mycoll", {capped:true,

size:100000}) 另:可隱式創建表。

創建表

Create INDEX idxname ON users(name)

db.users.ensureIndex({name:1})

創建索引

Create INDEX idxname ON users(name,ts DESC)

db.users.ensureIndex({name:1,ts:-1})

創建索引

Insert into users values(1, 1)

db.users.insert({a:1, b:1})

插入記錄

Select a, b from users

db.users.find({},{a:1, b:1})

查詢表

Select * from users

db.users.find()

查詢表

Select * from users where age=33

db.users.find({age:33})

條件查詢

Select a, b from users where age=33

db.users.find({age:33},{a:1, b:1})

條件查詢

select * from users where age<33

db.users.find({'age':{$lt:33}})

條件查詢

select * from users where age>33 and age<=40

db.users.find({'age':{$gt:33,$lte:40}})

條件查詢

select * from users where a=1 and b='q'

db.users.find({a:1,b:'q'})

條件查詢

select * from users where a=1 or b=2

db.users.find( { $or : [ { a : 1 } , { b : 2 } ] } )

條件查詢

select * from users limit 1

db.users.findOne()

條件查詢

select * from users where name like "%Joe%"

db.users.find({name:/Joe/})

模糊查詢

select * from users where name like "Joe%"

db.users.find({name:/^Joe/})

模糊查詢

select count(1) from users

Db.users.count()

獲取表記錄數

select count(1) from users where age>30

db.users.find({age: {'$gt': 30}}).count()

獲取表記錄數

select DISTINCT last_name from users

db.users.distinct('last_name')

去掉重複值

select * from users ORDER BY name

db.users.find().sort({name:-1})

排序

select * from users ORDER BY name DESC

db.users.find().sort({name:-1})

排序

EXPLAIN select * from users where z=3

db.users.find({z:3}).explain()

獲取存儲路徑

update users set a=1 where b='q'

db.users.update({b:'q'}, {$set:{a:1}}, false, true)

更新記錄

update users set a=a+2 where b='q'

db.users.update({b:'q'}, {$inc:{a:2}}, false, true)

更新記錄

delete from users where z="abc"

db.users.remove({z:'abc'})

刪除記錄

 

db. users.remove()

刪除所有的記錄

drop database IF EXISTS test;

use test

db.dropDatabase()

刪除數據庫

drop table IF EXISTS test;

db.mytable.drop()

刪除表/collection

 

db.addUser(‘test’, ’test’)

添加用戶

readOnly-->false

 

db.addUser(‘test’, ’test’, true)

添加用戶

readOnly-->true

 

db.addUser("test","test222")

更改密碼

 

db.system.users.remove({user:"test"})

或者db.removeUser('test')

刪除用戶

 

db.system.users.find()

查看用戶列表

 

show users

查看當前庫所有用戶

 

db.printCollectionStats()

查看各collection的狀態

 

db.printReplicationInfo()

查看主從複製狀態

 

show profile

查看profiling

 

db.copyDatabase('mail_addr','mail_addr_tmp')

拷貝數據庫

 

db.users.dataSize()

查看collection數據的大小

 

db. users.totalIndexSize()

查詢索引的大小


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章