首页 > 数据库技术 > 详细

python和mongodb简单交互

时间:2018-12-19 14:46:04      阅读:139      评论:0      收藏:0      [点我收藏+]

 

1.安装pymongo:

pip3 install pymongo
技术分享图片

2.pymongo的简单用法:

# /usr/bin/env python3
import pymongo


class Mymongo(object):
    def __init__(self, host, port=27017):
        try:
            self.conn = pymongo.MongoClient(host=host, port=port)
        except Exception as e:
            print("连接失败", e)
        else:
            print(‘连接成功‘)

    def add(self, p_dict):
        res = self.conn.testdb.testcol.insert(p_dict)  # insert需要传入字典
        if res:
            print(‘插入成功‘)

    def show(self):
        res = self.conn.testdb.testcol.find()  # find()返回一个可迭代对象
        for i in res:
            print(i)

    def mod(self, before, after):   # 需要传入字典
        res = self.conn.testdb.testcol.update(before, after)
        if res:
            print("修改成功", res)

    def rem(self, p_dict):
        res = self.conn.testdb.testcol.delete_one(p_dict)
        if res:
            print(‘删除成功‘)

if __name__ == "__main__":
    mymongo = Mymongo(‘192.168.26.135‘)
    mymongo.add({"name": ‘Tom‘})
    mymongo.show()
    mymongo.mod({"name": ‘Tom‘}, {"name": ‘Jerry‘})
    mymongo.show()
    mymongo.rem({"name": ‘Jerry‘})
    mymongo.show()

python和mongodb简单交互

原文:https://www.cnblogs.com/drizzle-xu/p/10143030.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!