1.mongo 远程连接
配置mongodb.conf,注释掉bind_ip
#bind_ip = 127.0.0.1 //注释此行
启用认证登陆
auth = true //将此行前的注释去掉
登陆(authenticationDatabase 验证数据库)
mongo host:port/dbname -u user-p password --authenticationDatabase dbname
mongo 127.0.0.1:27017/admin -u root -p 123456 --authenticationDatabase admin
正确关闭mongod 的方法
use admin
db.shutdownServer()
用户操作
认证
db.auth("user","password")
全部用户
show users // db.system.users.find()
// 新建用户
// 超级用户 root
db.createUser({user: "root",pwd: "123456",roles: [ "root" ]})
// 用户管理权限 userAdminAnyDatabase
db.createUser({user:"userAdmin",pwd:"123456",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})
// 数据库管理权限 dbAdminAnyDatabase
db.createUser({user:"dbAdmin",pwd:"123456",roles:[{role:"dbAdminAnyDatabase",db:"admin"}]})
// 数据读写用户 readWriteAnyDatabase
use test
db.createUser({user:"sa",pwd:"sa",roles:[{role:"readWrite",db:"test"}]})
// 已废弃的方法 相当于新建 { "user" : "root", "roles" : [ "dbOwner" ] }
// db.addUser("root","123456")
// 修改密码 db.changeUserPassword("root", "root")
// 删除原用户 db.dropUser("test") // db.system.users.remove({user:"test"});
角色权限
展示角色 show roles;
// 查看当前用户的权限 db.runCommand({usersInfo:"root",showPrivileges:true})
// 查看角色权限 db.getRole( "dbAdminAnyDatabase", { showPrivileges: true } )
集合(collection)文档(JSON)操作
展示集合 show collections;
查询数据 db.collection.find(query) // query可以是 ObjectId("24length")
查询一条 db.collection.findOne(query) // query可以是 ObjectId("24length")
插入数据 db.collection.insert(JSON)
删除数据 db.collection.remove(query)
更新数据 db.collection.update(queryjson,JSON[,{multi:true}]) // 及时匹配多条也只修改一条 ,可选项mulit:true时更新多条
删除集合 db.collection.drop()
添加或更新数据 db.collection.save(JSON) // JSON没有_id是insert否则是upsert
集合名的长度不能超过121字节,是因为集合命名空间中需要额外6个字节 .$_id_ ,放在一起是127个字节
更新修改器
1.增加、修改、删除
$set 增加或修改建对应的值
db.foo.update({"_id" : ObjectId("...")},{"$set":{"total":1,coll:[{"json1":"jsonV"},{"key":"value"}]}})
$unset 删除键对应的值
db.foo.update({"_id" : ObjectId("...")},{"$unset":{"total":null,coll:null}})
2.计数器
$inc 增加或减少数字 只能用于整数、长整数或双精度浮点数
db.foo.update({"_id":ObjectId("...")},{"$inc":{"total":-1}})
3.数组修改器
$push 新增或向尾部插入一个元素 一次只能插入一个
db.foo.update({"_id" : ObjectId("...")},{"$push":{coll:"a"}})
$ne 查询是否不存在某个元素 从查询的角度避免重复
db.foo.update({"_id" : ObjectId("..."),"coll":{"$ne":"a"}},{"$push":{coll:"a"}})
$addToSet 不设置重复值 从数组元素值的角度避免重复数据
db.foo.update({"_id" : ObjectId("54c25d065478a3459336bab0")},{"$addToSet":{coll:"c"}})
$each 将数组拆分,实现批量插入
可以跟$addToSet结合使用
db.foo.update({"_id" : ObjectId("54c25d065478a3459336bab0")},{"$addToSet":{coll:{"$each":["a","b","c","d"]}}})
$pop 栈的方式删除一端元素
负数从左移除一位,null/0/正数从右移除一位
db.foo.update({"_id" : ObjectId("54c25d065478a3459336bab0")},{"$pop":{"coll":1}})
$pull 删除匹配元素
db.foo.update({"_id" : ObjectId("54c25d065478a3459336bab0")},{"$pull":{"coll":5}})
4.数组定位修改器 $
通过下标(0开始)或定位操作符$(有问题)
db.foo.update({"_id" : ObjectId("54c25d065478a3459336bab0")},{"$set":{"coll.0":{"k0":"v0"}}})
5.upsert
创建或更新文档 update第三个参数为true,表示这是个upsert,如果不存在,查询条件会被当做文档的一部分
db.foo.update({"a":"b"},{"$inc":{"total":1}},true)
6.update 第四个参数
代表更新所有匹配到的文档,默认只更新第一个匹配到的文档
db.foo.update({"a":"b"},{"$inc":{"total":1}},false,true)
7.返回更新状态 getLastError
主要对写操作有用,写操作默认不会有返结果:这样就节约了客户端在写操作时等待客户端/服务器之间往返时间
db.runCommand({getLastError:1}) // 等价于 db.getLastErrorObj() 不等价于db.getLastError()
选项
fsync 当没有使用日志功能运行mongod(--nojournal)时,同步的选项强制数据库在同步完所有文件后才返回。 db.runCommand({getlasterror:1,fsync:true})
j:当j=true时,getlasterror调用等待日志提交后才返回。如果服务器没有启用日志功能,它立即返回,并且成功 db.runCommand({getlasterror:1,j:true})
w:客户端可以阻塞直到一个写操作被复制到N个服务器。wtimeout可以联合w一起使用。默认是没有超时(永久等待)db.getLastError(2, 5000) // w=2, timeout 5000ms
返回值
这个命令的返回值是一个多字段的对象。常用的字段已经列在下面;这里可能还有其他字段。
- ok - 为真的话表示getLastError命令成功完成了。它并不表示上一次没有错误。
- err - 如果非空,表示有错误出现。值是一个错误正文的描述。
- code - 如果设置了,表示出现的错误码。
- connectionId - 连接的id。
- lastOp - 上一次操作的op-id
对于更新:
- n - 如果一次更新完成了,它是更新的文档个数。
使用了w:<n>/<tag>
- wnote - 如果设置了,表示这里有些不寻常的事情发生,涉及使用w:
- wtimeout - 如果超时了,设置该值为真
- waited - 如果超时了,标记等到了多久,单位毫秒
- wtime - 花在等待操作完成的时间
JSON操作
赋值
foo.key1 = foo.key2
删除某个属性
delete foo.key
其他
展示状态 show dbs;
可以直接使用ObjectId("123456789012345678901234")
0x00 MongoDB权限介绍
服务器配置: /etc/mongod.conf
# mongod.conf #where to log logpath=/var/log/mongodb/mongod.log # 以追加方式写入日志 logappend=true # fork and run in background fork=true # 端口 #port=27017 # 数据库文件保存位置 dbpath=/var/lib/mongo # location of pidfile pidfilepath=/var/run/mongodb/mongod.pid # Listen to local interface only. Comment out to listen on all interfaces. bind_ip=127.0.0.1 # Disables write-ahead journaling # nojournal=true # Enables periodic logging of CPU utilization and I/O wait # 启用定期记录CPU利用率和 I/O 等待 #cpu=true # Turn on/off security. Off is currently the default # 是否以安全认证方式运行,默认是不认证的非安全方式 #noauth=true #auth=true # Verbose logging output. # 详细记录输出 #verbose=true # Inspect all client data for validity on receipt (useful for # developing drivers) # 用于开发驱动程序时的检查客户端接收数据的有效性 #objcheck=true # Enable db quota management # 启用数据库配额管理,默认每个db可以有8个文件,可以用quotaFiles参数设置 #quota=true # Set oplogging level where n is # 设置oplog记录等级 # 0=off (default) # 1=W # 2=R # 3=both # 7=W+some reads #diaglog=0 # Ignore query hints # 忽略查询提示 #nohints=true # Enable the HTTP interface (Defaults to port 28017). # 禁用http界面,默认为localhost:28017 #httpinterface=true # Turns off server-side scripting. This will result in greatly limited # 关闭服务器端脚本,这将极大的限制功能 # functionality #noscripting=true # Turns off table scans. Any query that would do a table scan fails. # 关闭扫描表,任何查询将会是扫描失败 #notablescan=true # Disable data file preallocation. # 关闭数据文件预分配 #noprealloc=true # Specify .ns file size for new databases. # 为新数据库指定.ns文件的大小,单位:MB # nssize=<size> # Replication Options # in replicated mongo databases, specify the replica set name here #replSet=setname # maximum size in megabytes for replication operation log #oplogSize=1024 # path to a key file storing authentication info for connections # between replica set members #keyFile=/path/to/keyfile