1. 程式人生 > >python 資料庫 mongodb

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