为数据库添加用户和权限
db.createUser({user:'root',pwd:'root',roles:[role:'root',db:'test']})
: 为当前的db创建一个用户mongod --auth
: 开启服务并启动认证- 连接数据库时需要输入认证信息
数据库操作
- 创建数据库:
use test
就会创建对应的数据库 - 删除数据库:
test.dropDatabase()
表(集合)操作
- 增:
db.people.insert({name:'test',age:22,sex:'male'})
- 删:
db.people.remove({name:'test'})
- 改:
db.people.update({name:'test'},{$set:{name:'demo'}})
- 查:
db.people.find({name:'tets'},{age:true,sex:1}).pretty()
第二个参数来过滤要查找的字段 - 删表:
db.people.drop()
- 改补充:
db.collection.update(criteria,objNew,upsert,multi)
upsert[true:不存在这条记录时插入,false:不插入],multi:查询出来的记录全部更新
不等修饰符
$lt
: less-than小于$lte
: less-than-equal小于等于$gt
: greater-than大于$gte
: greater-than-equal大于等于$ne
: not-equal不等于
多条件查询
db.people.find({age:{$in:[10,20]}})
:查找年龄为10和20的db.people.find({$or:[{name:'test'},{sex:'female']})
:查找名字为test或性别为女的db.people.find({$and:[{name:'test',{sex:'male'}]})
:查找名字test且性别为male的db.people.find({age:{$not:{$eq:22}}})
:查找年龄不为22的
数组查询
- 查询数组包含某属性
db.people.find({interest:'听歌'})
查找interest数组中包含'听歌'的所有 db.people.find({interest:{$all:["看电影","看书"]}})
db.people.find({interest:{$in:['游戏','打球']}})
查找兴趣是游戏和打球中的db.people.find({interest:{$size:2}})
查找兴趣长度为2db.people.find({},{interest:{$slice:1}})
只展示兴趣的一项,如果-1则显示最后一个
find查找后面的参数
limit(2)
从数据库中取出的数量skip(2)
跳过几个再取db.people.find({$where:'this.age>20'})
查找年龄大于20的文档