本文實例講述了mongodb基本命令。分享給大家供大家參考,具體如下:
1 切換數據庫
1
|
use admin; |
2 查看當前數據庫
1
|
db; |
2.1 查看所有數據庫
1
|
show dbs; |
3 查看當前數據庫下面的表
1
|
show collections; |
4 刪除數據庫
1
2
3
|
use test; db.dropDatabase(); #刪除當前數據庫 show dbs; #驗證刪除結果 |
5 刪除集合或者表
1
|
db.table_name. drop (); #刪除表 table_name |
6 查看賬號信息
1
2
3
4
5
6
|
mongo --port=23000 use admin; db.auth( 'username' , 'password' ) db.system.users.find().pretty() #查看所有賬號信息 show users; #查看當前賬號信息 db.getUser( 'username' ) #查看指定用戶的信息 |
7 使用gzip壓縮的方式備份與恢復,注意只要換個命令就行,后面的不變,這里沒用設置用戶名和密碼
1
2
3
|
mongodump --port=23000 --archive=/data/mongo_backup/testdb-2.20191203.gz --db testdb-2 --gzip mongorestore --port=23000 --archive=/data/mongo_backup/testdb-2.20191203.gz --db testdb-2 --gzip ** 這種備份方式生成一個gzip文件,解壓后也是一個文件,將所有內容都放到一個文件里面 |
8 不壓縮的方式備份
1
2
3
|
mongodump --port=23000 --db=testdb-2 -o /data/mongo_backup/20191203 mongorestore --port=23000 --db=testdb-2 --drop /data/mongo_backup/20191203/testdb-2 **經過這種方式備份,每個表通常就兩個文件:.bson和.metadata.json |
9 在shell中使用mongo命令查詢
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# 使用eval mongo ip:port/ database --eval "" [root@localhost ~]# mongo localhost:23000/testdb-2 --eval "printjson(db.table1.findOne())" MongoDB shell version v3.6.13 connecting to : mongodb://localhost:23000/testdb-2?gssapiServiceName=mongodb Implicit session: session { "id" : UUID( "e87ef5ae-a6b7-47d6-a91c-65f3a0b81ac0" ) } MongoDB server version: 3.6.13 { "_id" : ObjectId( "5de60a767321940034390f16" ), "id" : 129, "name" : "hehe" } #使用 --quiet 去掉不必要的信息 [root@localhost ~]# mongo localhost:23000/testdb-2 --quiet --eval "printjson(db.table2.findOne())" { "_id" : ObjectId( "5de615b8eac07a724c6911b6" ), "id" : 6, "name" : "hehe" } |
1
2
3
4
5
6
7
|
#刪除表 [root@localhost ~]# mongo localhost:23000/testdb-2 --eval "db.table1.drop();" MongoDB shell version v3.6.13 connecting to : mongodb://localhost:23000/testdb-2?gssapiServiceName=mongodb Implicit session: session { "id" : UUID( "0cf5b11f-c6ef-417c-8bbd-a2f8414f589c" ) } MongoDB server version: 3.6.13 true |
10 shell腳本中使用mongo命令
1
2
3
4
5
6
7
8
9
|
#!/bin/bash mongo localhost:23000/testdb-2 <<EOF var cursor =db.table2.find(); while ( cursor .hasNext()){ var item = cursor . next (); print(item. name ); } EOF |
1
2
3
4
5
6
7
8
9
10
11
|
#傳參的方式 #!/bin/bash table_name=$1 mongo localhost:23000/testdb-2 <<EOF var cursor =db.${table_name}.find(); while ( cursor .hasNext()){ var item = cursor . next (); print(item. name ); } EOF |
希望本文所述對大家MongoDB數據庫程序設計有所幫助。
原文鏈接:https://www.cnblogs.com/mmyy-blog/p/11977914.html