Python连接MongoDB【pymongo】

#!/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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值