python 数据库 mongodb

#coding=utf-8

import pymongo
#print pymongo.__version__

client = pymongo.MongoClient(host='127.0.0.1',port=27017)
db = client.test
collection = db.students
student = {
    'id':'20170905',
    'name':'mary',
    'age':20,
    'gender':'girl'
}
result  = collection.insert(student)  # 插入数据
print result
student = {
    'id':'20170906',
    'name':'lili',
    'age':19,
    'gender':'girl'
}
result  = collection.insert_one(student) # 插入数据
print result
print result.inserted_id

student1 = {
    'id':'20170907',
    'name':'lulu',
    'age':19,
    'gender':'girl'
}
student2 = {
    'id':'20170908',
    'name':'lisa',
    'age':19,
    'gender':'girl'
}
result = collection.insert_many([student1,student2])  # 插入多条
print result.inserted_ids

result = collection.find_one({'name':'lisa'})  # 查询一条
print result  # 输出多了_id 属性
print type(result)  # 字典类型

result = collection.find({'age':19})  # 查询多条
for res in result:
    #print res
    pass


results = collection.find({'age':{'$gt':19}}) # 大于20
'''
$lt 小于  $gt 大于  $lte 小于等于   $gte 大于等于 $ne 不等于  $in 在范围内  $nin 不在范围内
'''
for res in results:
    print res

results = collection.find({'name':{'$regex':'^m.*'}}) # 正则匹配查询
for res in results:
    print '正则',res

results = collection.find().sort('id',pymongo.ASCENDING)    # 升序排序     pymongo.DESCENDING 降序
print [result['name'] for result in results]

results = collection.find().sort('id',pymongo.ASCENDING).skip(2) # 偏移  # 忽略前两个元素
print [result['name']for result in results]

# 更新
condition = {'name':'mary'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update(condition,student)  # 不推荐使用,会把之前的数据全部用student替换掉
print '更新结果为:',result

# 更新一条
condition = {'name':'lulu'}
student = collection.find_one(condition)
student['age'] = 25
del student['_id']  # 删除在_id,否则无法更新
result = collection.update_one(condition,{'$set':student})
print '利用set更新后的结果:',result

#更新多条
condition = {'age':{'$gt':20}}
result = collection.update_many(condition,{'$inc':{'age':1}}) # 增加1
print result

#删除
result = collection.remove({'name':'haha'})
print result

猜你喜欢

转载自blog.csdn.net/nanxiaoting/article/details/82721083