连接数据库
import pymongo
client = pymongo.MongoClient(host='localhost', port=2701
指定数据库
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
# or
db = client['test']
插入数据
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
# or
db = client['test']
# 指定集合
collection = db.student
# or
collection = db['student']
student = {
'id' : '2019210050',
'user' : 'wiselisx',
'age' : 22,
'gender' : 'male'
}
student1 = {
'id' : '2019210050',
'user' : 'wiselisx',
'age' : 23,
'gender' : 'male'
}
# 插入单条数据
result = collection.insert_one(student)
# 插入多条数据
result = collection.insert_many([student, student1])
查询数据
# 查询名字为Mikes的数据
result = collection.find_one({'name': 'Mike'})
# 查询所有名字为Mikes的数据
result = collection.find({'name': 'Mike'})
# 查询年龄大于20的数据
result = collection.find({'age': {'$gt': 20}})
# 正则表达式查询
result = collection.find({'name': {'$regex': '^M.*'}})
计数
# 计数
count = collection.find().count()
# 符合某个条件的计数
count = collection.find({'age': {'$gt': 20}}).count()
排序
# 排序
results = collection.fin().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])
偏移
# 排序之后只取几个结果数
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
# 限制取几个数
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
更新数据
# 更新单条数据
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update_one(condition, {'$set': student})
# 更新多条数据
condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
删除
# 删除单条数据
condition = {'name': 'Kevin'}
result = collection.delete_one(condition)
# 删除多条数据
condition = {'age': {'$gt': 20}}
result = collection.delete_many(condition)