Mongodb增、删、改、查:
增:
# 新增 pymongo
Image_Push.<集合名>.insert_one({'name': '李四', 'age': '15'}) # 增加一条数据
删:
# 删除一条数据 pymongo
Image_Push.<集合名>.delete_one({'name': '李四', 'age': '15'}) # 增加一条数据
改:
# 修改、更新 pymongo
Image_Push.<集合名>.update({'age': '15'},{"$set": {'age': 30}}) # 查找age=15的数据, 更新为 age=30
查:
db.集合名.find() # 查询集合中的所有数据
db.集合名.find({'age': '1'}) # 查询 集合中 age = 1 的数据
db.集合名.find({'age': '6', 'sex': '男'}) # 查询集合中 同时满足 age=6 和 sex=男 的数据 and(与操作)
db.集合名.find('$or': [{'age': '6'},{'sex': '男'}]) # 查询集合中 满足 age=6 或者 sex=男 的数据 or(或操作)
db.集合名.find('$or': [{'age': '6'},{'sex': '男'}]) # 查询集合中 满足 age=6 或者 sex=男 的数据 or(或操作)
db.集合名.find({'city': '北京', '$or': [{'age': '6'},{'sex': '男'}]}) # 与或同时操作 满足 city=北京, age=6或sex=男的数据
#使用第二个参数,指定显示的列 (1显示 0 不显示)
db.集合名.find({'age': '1'}, {'age':1}) # 查询 集合中 age=1 的数据 只显示 age列
db.集合名.find({'age': '1'}, {'age':0}) # 查询 集合中 age=1 的数据 显示除了 age列
db.集合名.find({'age': '1'}, {'age':0, '_id':0}) # 查询 集合中 age=1 的数据 显示除了 age列 把 '_id' 也去掉
# 使用正则查询数据库
db.test.find({"title":{"$regex":".*<包含内的数据>.*"}})
# 随机查询30条数据 pymongo
Image_Push.<集合名>.aggregate([{"$sample": {"size": 30}}])
操作符:
$gt # 大于
$lt # 小于
例如: db.集合名.find({'age': {'$lt': '30'}}) 查询 age <= 30 的数据
$eq # 等于
$gte # 大于等于
$lte # 小于等于
$ne # 不等于
$in # in 在里面
$nin # not in 不在里面
$not # 取反
$exists # 是否存在 布尔值 ## db.集合名.find({'age': {'$exists': True}}) ## 集合中存在age的数据
复杂查询:
测试数据: {'status': ['age': '6'], 'sex': '男'}
mongodb单个数据下存在 [ ]列表的时候,用.方法查询
例如:db.集合名.find({'status.age': '6'})
Mogodb排序分页:
1.准备:
use test3
db.c1.insert({_id:1,name:"a",sex:1,age:1})
db.c1.insert({_id:2,name:"b",sex:1,age:2})
db.c1.insert({_id:3,name:"c",sex:2,age:3})
db.c1.insert({_id:4,name:"d",sex:2,age:4})
db.c1.insert({_id:5,name:"e",sex:2,age:5})
2. 排序:
语法:db.<集合名>.find().sort(json数据)
# 说明:键——就是要排序的列/字段、值:1是升序,-1是降序
# 例如:db.c1.find().sort({age:-1}) # c1是由开始写入数据时隐式创建
3. 分页:
语法:db.<集合名>.find().sort().skip(数字).limit(数字)
# skip——跳过指定数据数量(可选),查询新的数据 # 第一页不需要跳过,因为是新数据
# limit——查询指定数量数据
# 例如:db.c1.find().sort({age:-1}).limit(2) # 查询降序 两条数据
# 例如:db.c1.find().sort({age:-1}).skip(2).limit(3) # 查询降序 跳过两条数据 ,显示三条数据
# skip计算公式:(当前页 - 1)* 每页显示数量
4. 小总结:
db.<集合名>.find()
.sort({列:1/-1})——排序
.skip(数字)——跳过指定数量
.limit(数字)——限制查询条数
.count()——统计总数量
如果不够,在百度ro谷歌