Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 知乎專欄 | Search | Email

48.3. 命令工具

48.3.1. mongo shell

48.3.1.1. eval

		
# mongo
MongoDB shell version: 2.2.3
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
	http://docs.mongodb.org/
Questions? Try the support group
	http://groups.google.com/group/mongodb-user
>
		
		

3.4

		
[root@netkiller ~]# mongo
MongoDB shell version v3.4.1
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.1
Server has startup warnings: 
2017-01-03T11:26:57.516+0800 I CONTROL  [initandlisten] 
2017-01-03T11:26:57.516+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-01-03T11:26:57.516+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2017-01-03T11:26:57.516+0800 I CONTROL  [initandlisten] 
2017-01-03T11:26:57.516+0800 I CONTROL  [initandlisten] 
2017-01-03T11:26:57.516+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2017-01-03T11:26:57.516+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2017-01-03T11:26:57.516+0800 I CONTROL  [initandlisten] 
2017-01-03T11:26:57.516+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2017-01-03T11:26:57.516+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2017-01-03T11:26:57.516+0800 I CONTROL  [initandlisten] 
>
		
		
# mongo 127.0.0.1:27017/admin --eval "db.stats()"		
		

48.3.1.2. help

help

db.help()                    help on DB methods
db.foo.help()                help on collection methods
		

48.3.1.3. show 查看命令

48.3.1.3.1. show dbs

show dbs show database names

			
> show dbs
local	(empty)
logging	0.203125GB
test	0.203125GB
			
			
48.3.1.3.2. show collections

show collections show collections in current database

			

> show collections
bios
system.indexes
			
			

另一種用法是show tables

			
> show tables
bios
system.indexes
			
			
48.3.1.3.3. show users

show users show users in current database

			

			
			
48.3.1.3.4. show profile

show profile show most recent system.profile entries with time >= 1ms

			
> show profile
db.system.profile is empty
Use db.setProfilingLevel(2) will enable profiling
Use db.system.profile.find() to show raw profile entries
			
			

48.3.1.4. 切換資料庫

		
use <db name>                set curent database to <db name>

> use logging
switched to db logging
		
		

48.3.1.5. 記錄管理

48.3.1.5.1. save

存儲嵌套的對象

			
db.foo.save({'name':'neo','address':{'city':'shenzhen','post':518000},'phone':[13113668890,13322993040]})
			
			

存儲數組對象

			
db.foo.save({'Uid':'netkiller@msn.com','phone':['13322993040','13113668890']})
			
			
48.3.1.5.2. insert
			
db.bios.insert(
   {
     _id: 1,
     name: { first: 'John', last: 'Backus' },
     birth: new Date('Dec 03, 1924'),
     death: new Date('Mar 17, 2007'),
     contribs: [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ],
     awards: [
               {
                 award: 'W.W. McDowell Award',
                 year: 1967,
                 by: 'IEEE Computer Society'
               },
               {
                 award: 'National Medal of Science',
                 year: 1975,
                 by: 'National Science Foundation'
               },
               {
                 award: 'Turing Award',
                 year: 1977,
                 by: 'ACM'
               },
               {
                 award: 'Draper Prize',
                 year: 1993,
                 by: 'National Academy of Engineering'
               }
             ]
   }
)
			
			
48.3.1.5.3. update

根據query條件修改,如果不存在則插入,允許修改多條記錄

db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
			
48.3.1.5.4. remove

刪除uid=10的記錄

			
db.foo.remove({'uid':10})
			
			

刪除所有的記錄

db.foo.remove()
			
48.3.1.5.4.1. 刪除條件使用 _id
db.foo.remove({ "_id" : ObjectId("56e10b66a22ef1b1408b4567")})
				
48.3.1.5.5. find

查找所有 所有記錄

db.foo.find()                list objects in collection foo
db.foo.find( { a : 1 } )     list objects in foo where a == 1
			

查找一條記錄

db.foo.findOne()
			

根據條件檢索10條記錄

db.foo.find({'name':'neo'}).limit(10)
			

sort排序

db.foo.find({'name':'neo'}).sort({'Dt',-1})
db.foo.find().sort({'Ct':-1}).limit(1)
			

count記錄統計操作

db.foo.count()
			

distinct操作,去重複查詢指定列,

db.foo.distinct('name')
			

”>=”操作

			
db.foo.find({"timestamp": {"$gte" : 2}})
			
			

子對象的查找

db.foo.find({'address.city':'shenzhen'})
			
48.3.1.5.6. count()
			
> db.access.count()
51528
> db.access.count()
104401
			
			
48.3.1.5.7. group()

group()類似SQL中的Group by

			
> db.test.group({key: {remote_addr: true}, initial: {count: 0}, reduce: function(obj, prev) {prev.count++}});
[
	{
		"remote_addr" : "192.168.2.76",
		"count" : 3
	},
	{
		"remote_addr" : "192.168.2.70",
		"count" : 1
	}
]
			
			

48.3.1.6. 管道操作

		
cat data.bson | mongo test
		
		

48.3.1.7. shutdownServer

關閉MongoDB資料庫

		
db.shutdownServer()
		
		

48.3.2. mongodump - Backup

# mongodump -uneo -p -d test -o /tmp/
connected to: 127.0.0.1
Enter password:
Tue Sep  8 10:12:33.011 DATABASE: test	 to 	/tmp/test
Tue Sep  8 10:12:33.012 	test.system.indexes to /tmp/test/system.indexes.bson
Tue Sep  8 10:12:33.043 		 12 objects
Tue Sep  8 10:12:33.043 	test.bios to /tmp/test/bios.bson
Tue Sep  8 10:12:33.043 		 1 objects
Tue Sep  8 10:12:33.043 	Metadata for test.bios to /tmp/test/bios.metadata.json
Tue Sep  8 10:12:33.043 	test.system.users to /tmp/test/system.users.bson
Tue Sep  8 10:12:33.044 		 2 objects
Tue Sep  8 10:12:33.044 	Metadata for test.system.users to /tmp/test/system.users.metadata.json
Tue Sep  8 10:12:33.044 	test.fs.chunks to /tmp/test/fs.chunks.bson
Tue Sep  8 10:12:33.045 		 2 objects
Tue Sep  8 10:12:33.045 	Metadata for test.fs.chunks to /tmp/test/fs.chunks.metadata.json
Tue Sep  8 10:12:33.045 	test.fs.files to /tmp/test/fs.files.bson
Tue Sep  8 10:12:33.046 		 2 objects
Tue Sep  8 10:12:33.046 	Metadata for test.fs.files to /tmp/test/fs.files.metadata.json
Tue Sep  8 10:12:33.046 	test.images.chunks to /tmp/test/images.chunks.bson
Tue Sep  8 10:12:33.167 		 12 objects
Tue Sep  8 10:12:33.167 	Metadata for test.images.chunks to /tmp/test/images.chunks.metadata.json
Tue Sep  8 10:12:33.167 	test.images.files to /tmp/test/images.files.bson
Tue Sep  8 10:12:33.168 		 3 objects
Tue Sep  8 10:12:33.168 	Metadata for test.images.files to /tmp/test/images.files.metadata.json
Tue Sep  8 10:12:33.168 	test.img.chunks to /tmp/test/img.chunks.bson
Tue Sep  8 10:12:33.175 		 4 objects
Tue Sep  8 10:12:33.175 	Metadata for test.img.chunks to /tmp/test/img.chunks.metadata.json
Tue Sep  8 10:12:33.175 	test.img.files to /tmp/test/img.files.bson
Tue Sep  8 10:12:33.176 		 1 objects
Tue Sep  8 10:12:33.176 	Metadata for test.img.files to /tmp/test/img.files.metadata.json
		

48.3.2.1. 遠程備份

短參數

mongodump -h mongodb.example.net -p 27017 -u neo -p password -d netkiller -c yourcollection
			

長參數

mongodump --host mongodb.example.net --port 27017 --username backup --password passwd --db mdb --collection some			
			

48.3.2.2. 本地備份

通過指定dbpath在本地導出bson檔案

mongodump --dbpath /var/lib/mongodb --out /opt/backup --db test --username backup --password passwd			
			

48.3.3. mongorestore

直接從dump回覆備份

[root@netkiller www]# ls
backup  dump

[root@netkiller www]# mongorestore dump/		
		
# mongorestore -h 127.0.0.1 -u neo -p chen /tmp/test/
connected to: 127.0.0.1
Tue Sep  8 10:18:31.360 /tmp/test/system.users.bson
Tue Sep  8 10:18:31.360 	going into namespace [test.system.users]
Tue Sep  8 10:18:31.361 warning: Restoring to test.system.users without dropping. Restored data will be inserted without raising errors; check your server log
2 objects found
Tue Sep  8 10:18:31.361 	Creating index: { key: { _id: 1 }, ns: "test.system.users", name: "_id_" }
Tue Sep  8 10:18:31.406 	Creating index: { key: { user: 1, userSource: 1 }, unique: true, ns: "test.system.users", name: "user_1_userSource_1" }
Tue Sep  8 10:18:31.406 /tmp/test/img.chunks.bson
Tue Sep  8 10:18:31.406 	going into namespace [test.img.chunks]
Tue Sep  8 10:18:31.407 warning: Restoring to test.img.chunks without dropping. Restored data will be inserted without raising errors; check your server log
4 objects found
Tue Sep  8 10:18:31.409 	Creating index: { name: "_id_", key: { _id: 1 }, ns: "test.img.chunks" }
Tue Sep  8 10:18:31.409 	Creating index: { name: "files_id_1_n_1", key: { files_id: 1, n: 1 }, unique: true, ns: "test.img.chunks" }
Tue Sep  8 10:18:31.409 /tmp/test/fs.files.bson
Tue Sep  8 10:18:31.409 	going into namespace [test.fs.files]
Tue Sep  8 10:18:31.410 warning: Restoring to test.fs.files without dropping. Restored data will be inserted without raising errors; check your server log
2 objects found
Tue Sep  8 10:18:31.410 	Creating index: { name: "_id_", key: { _id: 1 }, ns: "test.fs.files" }
Tue Sep  8 10:18:31.410 /tmp/test/images.chunks.bson
Tue Sep  8 10:18:31.410 	going into namespace [test.images.chunks]
Tue Sep  8 10:18:31.411 warning: Restoring to test.images.chunks without dropping. Restored data will be inserted without raising errors; check your server log
12 objects found
Tue Sep  8 10:18:31.414 	Creating index: { name: "_id_", key: { _id: 1 }, ns: "test.images.chunks" }
Tue Sep  8 10:18:31.414 	Creating index: { name: "files_id_1_n_1", key: { files_id: 1, n: 1 }, unique: true, ns: "test.images.chunks" }
Tue Sep  8 10:18:31.414 /tmp/test/images.files.bson
Tue Sep  8 10:18:31.414 	going into namespace [test.images.files]
Tue Sep  8 10:18:31.414 warning: Restoring to test.images.files without dropping. Restored data will be inserted without raising errors; check your server log
3 objects found
Tue Sep  8 10:18:31.415 	Creating index: { name: "_id_", key: { _id: 1 }, ns: "test.images.files" }
Tue Sep  8 10:18:31.415 /tmp/test/fs.chunks.bson
Tue Sep  8 10:18:31.415 	going into namespace [test.fs.chunks]
Tue Sep  8 10:18:31.415 warning: Restoring to test.fs.chunks without dropping. Restored data will be inserted without raising errors; check your server log
2 objects found
Tue Sep  8 10:18:31.416 	Creating index: { name: "_id_", key: { _id: 1 }, ns: "test.fs.chunks" }
Tue Sep  8 10:18:31.416 	Creating index: { name: "files_id_1_n_1", key: { files_id: 1, n: 1 }, unique: true, ns: "test.fs.chunks" }
Tue Sep  8 10:18:31.416 /tmp/test/img.files.bson
Tue Sep  8 10:18:31.416 	going into namespace [test.img.files]
Tue Sep  8 10:18:31.417 warning: Restoring to test.img.files without dropping. Restored data will be inserted without raising errors; check your server log
1 objects found
Tue Sep  8 10:18:31.417 	Creating index: { name: "_id_", key: { _id: 1 }, ns: "test.img.files" }
Tue Sep  8 10:18:31.417 /tmp/test/bios.bson
Tue Sep  8 10:18:31.417 	going into namespace [test.bios]
Tue Sep  8 10:18:31.417 warning: Restoring to test.bios without dropping. Restored data will be inserted without raising errors; check your server log
1 objects found
Tue Sep  8 10:18:31.417 	Creating index: { key: { _id: 1 }, ns: "test.bios", name: "_id_" }
		

恢復到指定資料庫

# mongorestore -h 127.0.0.1 -d test123 /tmp/test
		

48.3.3.1. 遠程回覆

mongorestore --host mongodb.example.net --port 27017 --username backup --password password --db test --collection some /data/backup
			

48.3.3.2. 本地恢復

mongorestore --dbpath /var/lib/mongodb --journal /opt/backup
			

48.3.3.3. filter

如果只想恢復部分數據,可以使用--filter

$ mongorestore -h 127.0.0.1 -d test123 /tmp/test --filter '{"field": 1}'			
			

48.3.4. mongostat

# mongostat
connected to: 127.0.0.1
insert  query update delete getmore command flushes mapped  vsize    res faults   locked db idx miss %     qr|qw   ar|aw  netIn netOut  conn       time
    *0     *0     *0     *0       0     1|0       0   848m  1.92g   162m      0 wechat:0.0%          0       0|0     0|0    62b     4k     1   10:38:53
    *0     *0     *0     *0       0     1|0       0   848m  1.92g   162m      0 wechat:0.0%          0       0|0     0|0    62b     4k     1   10:38:54
    *0     *0     *0     *0       0     1|0       0   848m  1.92g   162m      0 wechat:0.0%          0       0|0     0|0    62b     4k     1   10:38:55
    *0     *0     *0     *0       0     1|0       0   848m  1.92g   162m      0 wechat:0.0%          0       0|0     0|0    62b     4k     1   10:38:56
    *0     *0     *0     *0       0     1|0       0   848m  1.92g   162m      0 wechat:0.0%          0       0|0     0|0    62b     4k     1   10:38:57
		

48.3.5. mongotop

# mongotop
connected to: 127.0.0.1

                            ns       total        read       write		2015-09-08T02:23:46
         passport.system.users         0ms         0ms         0ms
    passport.system.namespaces         0ms         0ms         0ms
       passport.system.indexes         0ms         0ms         0ms
           member.system.users         0ms         0ms         0ms
      member.system.namespaces         0ms         0ms         0ms
         member.system.indexes         0ms         0ms         0ms
		

48.3.6. mongofiles - Browse and modify a GridFS filesystem.

48.3.6.1. list 瀏覽檔案

# mongofiles list
connected to: 127.0.0.1
/etc/passwd	2176
/tmp/test1.php	192
			

			

48.3.6.2. put 上傳檔案

# mongofiles put /bin/ls
connected to: 127.0.0.1
added file: { _id: ObjectId('55ee4c68bd053b7418404c53'), filename: "/bin/ls", chunkSize: 261120, uploadDate: new Date(1441680488106), md5: "ca226dd605e91b72e0d2060a6357c28f", length: 109208 }
done!

# mongofiles list
connected to: 127.0.0.1
/etc/passwd	2176
/tmp/test1.php	192
/bin/ls	109208
			

上傳指定資料庫

# mongofiles put -d images -c img /etc/fstab
connected to: 127.0.0.1
added file: { _id: ObjectId('55ee4d5416377f58d0a9e714'), filename: "/etc/fstab", chunkSize: 261120, uploadDate: new Date(1441680724579), md5: "381185dc0c4807b88406b452b4acc2e8", length: 1067 }
done!

# mongofiles list -d images -c img
connected to: 127.0.0.1
/etc/fstab	1067
			
[提示]collection 參數有 bug 需要注意。

-c img 似乎無效,可能是mongofiles的bug. 使用PHP測試上傳是可以指定 collection,並且沒有任何問題。

				
# mongofiles put -d images --collection abc /etc/nfsmount.conf
connected to: 127.0.0.1
added file: { _id: ObjectId('55ee4f5ef4b26bc3189dc8a5'), filename: "/etc/nfsmount.conf", chunkSize: 261120, uploadDate: new Date(1441681246083), md5: "ce3b9fee8612087cbb69d46db34ce8ec", length: 3605 }
done!

# mongofiles -d images --collection abc list
connected to: 127.0.0.1
/etc/fstab	1067
/etc/passwd	2555
/etc/goaccess.conf	6956
/etc/krb5.conf	449
/etc/nfsmount.conf	3605

# mongo images
> show collections;
abc.fs.chunks
abc.fs.files
fs.chunks
fs.files
system.indexes
>

> db.abc.fs.files.find();
>
				
				

使用 --collection 參數可以看到abc已經創建,但我們去db.abc.fs.files.find();發現裡面沒有任何數據,檔案仍然被上傳到 abc.fs.files

48.3.6.3. get 下載

如果 /tmp/test123 存在則會覆蓋

# mongofiles get /tmp/test123
connected to: 127.0.0.1
done write to: /tmp/test123
			

-l 指定路徑,相當於另存。

# mongofiles get /tmp/test123 -l /tmp/aabbcc
connected to: 127.0.0.1
done write to: /tmp/aabbcc
			

48.3.6.4. delete 刪除

# mongofiles list 
connected to: 127.0.0.1
/etc/passwd	2176
/tmp/test1.php	192
/bin/ls	109208
/tmp/test123	6

# mongofiles delete /tmp/test123
connected to: 127.0.0.1
done!

# mongofiles list 
connected to: 127.0.0.1
/etc/passwd	2176
/tmp/test1.php	192
/bin/ls	109208