1.查询条件放在第一个大括号中:
查询年龄⼤于18或性别为男⽣,并且家乡为大理
db.stu.find({$or:[{age:{$gt:18}}, {gender:true}], hometown:'大理'})
2.第二个大括号放投影条件(控制那些现实出来):
查询所有学生信息,只显示姓名和年龄
db.stu.find({}, {name:1, age: 1})
3.排序:查询出来点sort:
根据性别降序, 再根据年龄升序
db.stu.find().sort({gender:-1, age: 1})
4.消除重复: db.集合名称.distinct('去重字段',{条件})
查询年龄大于20的学生的家乡, 不能重复
db.stu.distinct('hometown', {age:{$gt: 20}})
5.聚合是放在第一个大括号中:
db.stu.aggregate(
{$group:{_id:'$gender', counter:{$sum: 1}}}
)
6.多个聚合文档就要取别名:
db.t2.aggregate( {$group: {_id:{country:'$country',province:'$province',userid:'$userid' }}} )
7.数据库备份与恢复:
备份MongoDB数据库到桌面
mongodump -h 127.0.0.1:27017 -d MongoDB -o ~/Desktop
恢复MongoDB数据库为MongoDB2
mongorestore -h 127.0.0.1:27017 -d MongoDB2 --dir ~/Desktop/MongoDB
8.导入导出:
以json格式导出MongoDB数据库中stu集合, 文件名为stu.jsonlines
mongoexport -h 127.0.0.1:27017 -d MongoDB -c stu -o ~/Desktop/stu.jsonlines
以csv格式导出MongoDB数据库中stu集合, 导出字段:name, age, gender, hometown
mongoexport -h 127.0.0.1:27017 -d MongoDB -c stu -o ~/Desktop/stu.csv --type csv -f name,age,gender,hometown
导入stu.json到MongoDB数据中stu2集合中
mongoimport -h 127.0.0.1:27017 -d MongoDB -c stu2 --file ~/Desktop/stu.jsonlines
导入stu.csv到itcast数据中stu3集合中
mongoimport -h 127.0.0.1:27017 -d MongoDB -c stu3 --file ~/Desktop/stu.csv --type csv --headerline
9.权限管理:
改为认证模式:修改mongod.conf 文件, 增加:
security:
authorization: enabled
在admin数据库中创建管理员用户:
db.createUser({"user":"python","pwd":"python","roles":["root"]})
在指定数据库中创建一般用户:
db.createUser("user":"user1", "pwd":"pwd1", roles:["read"])
db.createUser("user":"user1", "pwd":"pwd1", roles:["readWrite"])
在指定数据库中认证登录:
db.auth('username': 'pwd')
10.与python的交互:
- 获取认证:client = MongoClient('mongodb://py6:123@127.0.0.1:27017')
- 获取操作集合:collection = client['数据库名']['集合名']
- 添加一条数据: insert_one
- 添加多条数据: insert_many(字典列表)
- 查找一条数据: find_one
- 查找全部数据: find, 返回一个游标对象, 只能遍历一次
- 更新一条数据 注意使用$set命令: update_one
- 更行全部数据: update_many
- 删除一条数据: delete_one
- 删除全部数据: delete_many