import pymongo
#连接指定服务器
client = pymongo.MongoClient(host='localhost',port=27017)
#获取本机的db实例test(没有的话就创建,有的话就返回这个数据化的实例)
db=client.test
#创建test数据库里的students数据表
collection = db.students
student1={
'id':'20170101',
'name':'Jordan',
'age':20,
'gender':'male'
}
student2 = {
'id':'20170102',
'name':'mike',
'age':18,
'gerder':'madam'
}
student_update = {
'id':'20170102',
'name':'carry',
'age':21,
'gerder':'madam'
}
#添加数据如果不指定_id字段,系统会默认生成一个objectID
collection.insert(student1)
collection.insert(student2)
#find查找返回符合条件的多个结果,查询条件使用字典指定,可使用多个字段
result_find = collection.find({'id':'20170102'})
result_find_one = collection.find_one({'gender':'madam'})
result_find_age = collection.find({'age':{'$gt':10}})
#返回一个游标,游标相当于一个迭代器,存取查询结果,可以使用next()获取一条结果
print(result_find.next())
#更新数据:
# 更新指定条件的数据,upsert为True指定更新符合条件数据,如果没有符合条件数据,执行插入操作。
#$set是mongodb内置函数,覆盖原始数据
collection.update({'id':'20170102'},{'$set':student_update},upsert=True)
result = collection.find({'id':'20170102'})
print(result.next())
#删除指定数据
collection.update({'id':'20170102'})
其他查询条件条件:
"""
$lt小于{'age':{'$lt':20}}
$lte小于等于{'age':{'$lt':20}}
$gt大于{'age':{'$gt':20}}
$gte大于等于{'age':{'$gt':20}}
$ne不等于{'age':{'$ne':20}}
$in在范围内{'age':{'$in':20}}
$nin不在范围内{'age':{'$nin':20}}
"""
python—pymongo包的用法
最新推荐文章于 2025-06-01 15:04:54 发布