#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pymongo import MongoClient
from datetime import datetime
from bson.objectid import ObjectId
class Config(object):
'''Mongo配置文件'''
host = 'localhost',
port = 27017
class TestMongo(object):
'''Mongo连接'''
def __init__(self):
self.config = Config()
self.client = MongoClient(self.config.host, self.config.port)
self.db = self.client['blog']
def add_one(self):
'''新增数据'''
post = {
'title':'新的标题5',
'content': '博客内容5......',
'created_at': datetime.now(),
'count_x': 1
}
return self.db.blog.posts.insert_one(post)
def get_one(self):
'''查询一条数据'''
return self.db.blog.posts.find_one()
def get_more(self):
'''查询多条数据'''
return self.db.blog.posts.find({'count_x':{'$gt':33}})
def get_one_form(self, oid):
'''查询指定id数据 '''
obj_id = ObjectId(oid) # id需要转换成ObjectId
return self.db.blog.posts.find_one({'_id': obj_id})
def update_one(self):
'''修改一条数据'''
return self.db.blog.posts.update_one({'_id':ObjectId('5b14c3879ea01d539c01c3dd')},{'$inc':{'count_x': 10}})
def update_many(self):
'''修改多条数据'''
return self.db.blog.posts.update_many({},{'$inc':{"count_x": 11}})
def delete_one(self):
'''删除一条数据'''
rest = self.db.blog.posts.delete_one({'_id':ObjectId('5b14c3879ea01d539c01c3dd')})
return rest
def delete_many(self):
'''删除多条数据'''
rest = self.db.blog.posts.delete_many({'count_x':{'$gt':33}})
return rest
def main():
obj = TestMongo()
# 新增一条数据
# rest = obj.add_one()
# print(rest.inserted_id)
# 查询一条数据
# rest = obj.get_one()
# print(rest['_id'])
# 查询多条数据
# rest = obj.get_more()
# for item in rest:
# print(item)
# 查询指定id数据
# rest = obj.get_one_form("5b14c3879ea01d539c01c3dd")
# print(rest)
# 修改一条数据
# rest = obj.update_one()
# print(rest.matched_count) # 匹配成功的条数
# print(rest.modified_count) # 修改成功的条数
# 修改多条数据
# rest = obj.update_many()
# print(rest.matched_count)
# print(rest.modified_count)
# 删除一条数据
# rest = obj.delete_one()
# print(rest, rest.deleted_count) # 返回删除成功的条数
# 删除
# rest = obj.delete_many()
# print(rest, rest.deleted_count)
if __name__ == '__main__':
main()
参考资料:
pymongo: http://api.mongodb.com/python/current/tutorial.html