MongoDB数据库(端口:27017)
1. MongoDB常用的操作
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
# 指定数据库test
db = client.test
# 指定集合
collection = db.students
# 插入数据
student1 = {
'id': '20180101',
'name': 'zhangsan',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '20180102',
'name': 'lisi',
'age': 20,
'gender': 'male'
}
result = collection.insert([student1, student2])
result = collection.insert_one(student1)
result = collection.insert_many([student1, student2])
# 查询
result = collection.find_one({'name': 'zhangsan'})
results = collection.find({'age': 20})
for res in results:
print(res)
# 年龄小于20的数据
results = collection.find({'age': {'$lt': 20}})
# 年龄小于等于20的数据
results = collection.find({'age': {'$lte': 20}})
# 年龄大于20的数据
results = collection.find({'age': {'$gt': 20}})
# 年龄大于等于20的数据
results = collection.find({'age': {'$gte': 20}})
# 年龄不等于20的数据
results = collection.find({'age': {'$ne': 20}})
# 年龄在[18, 25]范围内的数据
results = collection.find({'age': {'$in': [18,23]}})
# 年龄不在[18, 25]范围内的数据
results = collection.find({'age': {'$nin': [18,23]}})
# 正则查询,匹配以M开头的数据
results = collection.find({'name': {'$regex': '^M.*'}})
# 计数
num = collection.find({'age': 20}).count()
# 根据字段,升序ASCENDING/降序DESCENDING
results = collection.find().sort('name', pymongo.ASCENDING)
print(result['name'] for result in results)
# 偏移位置,skip(n)忽略前n个元素
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print(result['name'] for result in results)
# 限制返回结果个数limit(n),从左到右
results = collection.find().sort('name', pymongo.ASCENDING).limit(2)
print(result['name'] for result in results)
# 更新update()
condition = {'name': 'wangwu'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update(condition, student)
# $set操作符只更新student字典内存在的字段,其他字段不更新也不删除
result = collection.update(condition, {'$set': student})
# update_one()
result = collection.update_one(condition, {'$set': student})
# 查看获得匹配的数据条数和影响的数据条数
print(result.matched_count, result.modified_count)
# update_many()
condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 18})
# 查看获得匹配的数据条数和影响的数据条数
print(result.matched_count, result.modified_count)
# 删除
result = collection.remove({'name': 'zhangsan'})
result = collection.delete_one({'name': 'zhangsan'})
result = collection.delete_many({'age': {'$lt': 20})
持续跟新,更多MongoDB数据库知识,详见个人博客归纳。
欢迎留言补充,批评指正!