數(shù)據(jù)庫帳號的創(chuàng)建與使用
// mongodb 未開auth時 創(chuàng)建超級管理員
mongo --port 27017
use admin
db.createUser({user: 'root', pwd: 'root', roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]})
// 停止mongodb
kill -2 pid 或 db.shutdownServer()
// 重啟mongodb 開啟auth
mongo --auth --port 27017
use admin
db.auth('root', 'root')
// 切換到普通db
use students
db.createUser({user: 'std', pwd: 'stdpwd', roles: [role: 'readWrite', db: 'students']})
// 其他操作
db.getUser('std');
db.system.users.find({}); or show users
show collections
// 刪除某個collection
db.collectionName.drop()
// 之后訪問相應(yīng)的數(shù)據(jù)庫
mongo mongodb://std:stdpwd@120.12.12.1:27017/student
數(shù)據(jù)的備份還原
// 備份數(shù)據(jù), 使用mongodump
mongodump -h dbhost:27017 -d dbname -u username -p password -o dbdirectory
// 還原數(shù)據(jù)
mongorestore -h dbhost:27017 -d dbname -u username -p password dbdata
數(shù)據(jù)導(dǎo)入與導(dǎo)出
數(shù)據(jù)導(dǎo)出
mongoexport --host monogo_address --db db_name --collection collection_name --out output_file_name --fields "field_1, field_2" --type output_type_like_csv_default_json --jsonArray --limit limit_count --skip skip_count
注意:
- 導(dǎo)出類型為json時導(dǎo)出的數(shù)據(jù)中必然包括
_id
字段, 可設(shè)置--jsonArray
將數(shù)據(jù)從{}{}{}
轉(zhuǎn)成[{},{},{}]
- 導(dǎo)出類型為csv時必須指定
--fields
數(shù)據(jù)導(dǎo)入
mongoimport -h monogo_address --db db_name --collection collection_name --file output_file_name --type csv|json(default) --fields "field_1, field_2"
數(shù)組的更新
// collection 單條實(shí)例數(shù)據(jù)結(jié)構(gòu)
{
_id: '123',
arr: [
{name: 'a', age: 12, courses: [{name: 'c++', grade: 123}]},
{name: 'b', age: 13},
],
}
添加obj
到數(shù)組
- 添加不重復(fù)的
obj
--$addToSet
db.collection.update({_id: '123'}, {$addToSet: {arr: {name: 'c', age: 14}}})
- 添加可重復(fù)的
obj
--$push
嚴(yán)格匹配:db.collection.update({_id: '123'}, {$push: {arr: {name: 'a', age: 12}}})
匹配存在:`` - 一次添加多個
obj
--$push $each
db.collection.update({_id: '123'}, {$push: {arr: {$each: [{name: 'd', age: 15}, {name: 'e', age: 16}]}}})
$each
還可配合其他操作符使用:
- 設(shè)置數(shù)組的排序
$sort
db.collection.update({_id: '123'}, {$push: {arr: {$each: [{name: 'd', age: 15}, {name: 'e', age: 16}], $sort: {age: -1} }}})
設(shè)置數(shù)組按age由大到小排 - 設(shè)置插入的位置
$position
db.collection.update({_id: '123'}, {$push: {arr: {$each: [{name: 'd', age: 15}, {name: 'e', age: 16}], $position: 2 }}})
設(shè)置插入的位置在index為2處) - 設(shè)置數(shù)組的切除
$slice
db.collection.update({_id: '123'}, {$push: {arr: {$each: [{name: 'd', age: 15}, {name: 'e', age: 16}], $slice: -3 }}})
設(shè)置只留下后三個)
從數(shù)組中刪除特定obj
db.collection.update({_id:'123'}, {$pull: {name: 'a', age: 12}}})
更新數(shù)值中特定對象的特定key
- 一維數(shù)組
db.collection.update({_id: '123', 'arr.name': 'a'}, {$set: {'arr.$.age': 13}}})
- 多維數(shù)組
db.collection.update({_id: '123', 'arr.0.courses.0.name': 'c++'}, {$inc: {arr.0.courses.0.grade: 10}})
插入數(shù)據(jù)
- 批量插入數(shù)據(jù) (mongoDB V3.2)
db.collections.insertmany()