python操作数据库MongoDB常用的方法

**

python操作mongodb的基本常用方法

**

MongoDB是由C++语言编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,其内容存储形式类似JSON对象,它的字段值可以包含其他文档、数组及文档数组,非常灵活。在这一节中,我们就来看看Python 3下MongoDB的存储操作。

在这里插入图片描述

准备工作

所以开始之前我们要确保安装好Mongodb和启动其服务,并安装好python的pymongo,这次我们就展示一下如何操作常用的命令。 进入命令 mongo

python操作的三个必须步骤

import pymongo


class MyMongoDB():
    def __int__(self, database, collection):    #定义参数接收指定的数据库和集合
        self.client = pymongo.MongoClient()     #连接MongoDB
        Self.db = self.client[database]         #指定数据库
        self.col = self.db[collection]          #指定集合

定义一个类,然后将函数封装起来,这样我们就可以传入指定的数据库和集合,然后再封装到属性里面

student = MyMongoDB('one','student')
print(list(student.col.find()))

#输出[]

这个时候我们就可以实例化,我们可以去连接指定的数据库。我新建一个数据库和集合
因为one库里面没有数据所以不会显示
在这里插入图片描述

1.插入insert

 def insert(self, data, onlyOne = True):
        if not isinstance(onlyOne,bool):
            raise TypeError
        self.col.insert_one(data) if onlyOne else self.col.insert_many(data)

       

1.第一个参数接收我们需要的数据
2.第二个参数是默认参数,你是要插入一条数据还是多条数据,如果是插入一条那么就不需要传入第二 个参数,如果是插入多条数据,反之。
3.用isinstance判断,onlyOne是否为第二个参数的类型,然后返回类型错误
4.用三目运算

插入一条数据

student.insert({'name':'one','age':18})

#输出[{'_id': ObjectId('5fc60b76f27f7a7906239bb7'), 'name': 'one', 'age': 18}]

插入多条

# student.insert({'name':'one','age':18})
student.insert([{'name': 'two', 'age': '18'}, {'name': 'three', 'age': 18}])

#报错信息
Traceback (most recent call last):
  File "/home/bd/py_case/Mongodb.py", line 18, in <module>
    student.insert([{'name': 'two', 'age': '18'}, {'name': 'three', 'age': 18}])
  File "/home/bd/py_case/Mongodb.py", line 13, in insert
    self.col.insert_one(data) if onlyOne else self.col.insert_many(data)
  File "/home/bd/.virtualenvs/py3env/lib/python3.6/site-packages/pymongo/collection.py", line 692, in insert_one
    common.validate_is_document_type("document", document)
  File "/home/bd/.virtualenvs/py3env/lib/python3.6/site-packages/pymongo/common.py", line 505, in validate_is_document_type
    "collections.MutableMapping" % (option,))
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

Process finished with exit code 1

这个时候就会报错,因为我们默认是只插入一条数据,这个时候我们需要在后面加个false

student.insert([{'name': 'two', 'age': '18'}, {'name': 'three', 'age': 18}]False)

#输出
[{'_id': ObjectId('5fc60b76f27f7a7906239bb7'), 'name': 'one', 'age': 18}, {'_id': ObjectId('5fc60e6b615433bade3b2ce5'), 'name': 'two', 'age': '18'}, {'_id': ObjectId('5fc60e6b615433bade3b2ce6'), 'name': 'three', 'age': 18}]

2.查找find

    def find(self,query = None, onlyOne = True):
        if not isinstance(onlyOne, bool):
            raise TypeError
        return self.col.find_one(query) if onelyOne else self.col.find(query)

1.这里和插入一样,默认查找一条数据,true查一条,false查多条
2.self.col.find()是可以不传参数的,所以可以给他一个默认参数None

1.查找一条数据

print(student.find())

#输出
{'_id': ObjectId('5fc60e6b615433bade3b2ce5'), 'name': 'two', 'age': '18'}

2.带条件查询

print(student.find({'age':18}))


#输出
{'_id': ObjectId('5fc60e6b615433bade3b2ce6'), 'name': 'three', 'age': 18}

3.查找全部数据

print(student.find({'age':18}),False) #或者print(student.find(onlyOne = False)


#输出
[{'_id': ObjectId('5fc615669ccaa9d8775af296'), 'name': 'one'}, {'_id': ObjectId('5fc6156d286a7c9919d5b89c'), 'name': 'two', 'age': '18'}, {'_id': ObjectId('5fc6156d286a7c9919d5b89d'), 'name': 'three', 'age': 18}]

来看看Mongodb里面的是否有这3条数据
在这里插入图片描述
接下来就不多说其实思路都是差不多的

3.修改update

    def update(self, data, new_data, onlyOne=True):
        if not isinstance(onlyOne, bool):
            raise TypeError
        self.col.update_one(data, {'$set': new_data}) if onlyOne else self.col.update_many(data, {'$set': new_data})
#我们现在修改age,我插入age都是18,我现在修改为20
student.update({'age': {'$eq': 18}}, {'age': 20}, False)#修改多条数据

#输出
[{'_id': ObjectId('5fc6156d286a7c9919d5b89d'), 'name': 'three', 'age': 20}, {'_id': ObjectId('5fc61d605420c703577ad20b'), 'name': 'one', 'age': 20}, {'_id': ObjectId('5fc6205c3152ecb144288b5f'), 'name': 'two', 'age': 20}]

这里我分享一个操作符
在这里插入图片描述

4.删除delete

   def delete(self,data,onlyOne = True):
        if not isinstance(onlyOne,bool):
            raise TypeError
        self.col.delete_one(data) if onlyOne else self.col.delete_many(data)

删除数据

student.delete({'age': 20})#把第一条的数据给删了

#输出,这个时候没有one同学的数据了
[{'_id': ObjectId('5fc624c77dc2326e28c2b6c4'), 'name': 'two', 'age': 20}, {'_id': ObjectId('5fc624c77dc2326e28c2b6c5'), 'name': 'three', 'age': 20}]


student.delete({'age': 20},Fallse)#把所有数据删除
#或者可以直接这样student.delete({},Fallse)
#输出
[]

MongoDB里面的显示已经查不到了,以上就是python对MongoDB增删改查的操作,封装好后可以创建更多的实例!

在这里插入图片描述

最后附上全部代码

import pymongo


class MyMongoDB:
    def __init__(self, database, collection):  # 定义参数接收指定的数据库和集合
        self.client = pymongo.MongoClient()  # 连接MongoDB
        self.db = self.client[database]  # 指定数据库
        self.col = self.db[collection]  # 指定集合

    def insert(self, data, onlyOne=True):
        if not isinstance(onlyOne, bool):
            raise TypeError
        self.col.insert_one(data) if onlyOne else self.col.insert_many(data)

    def find(self, query=None, onlyOne=True):
        if not isinstance(onlyOne, bool):
            raise TypeError
        return self.col.find_one(query) if onlyOne else self.col.find(query)

    def update(self, data, new_data, onlyOne=True):
        if not isinstance(onlyOne, bool):
            raise TypeError
        self.col.update_one(data, {'$set': new_data}) if onlyOne else self.col.update_many(data, {'$set': new_data})

    def delete(self, data, onlyOne=True):
        if not isinstance(onlyOne, bool):
            raise TypeError
        self.col.delete_one(data) if onlyOne else self.col.delete_many(data)


# student = MyMongoDB('one', 'student')
# student.insert({'name': 'one', 'age': 18})
# # student.insert([{'name': 'two', 'age': 18}, {'name': 'three', 'age': 18}],False)
# # print(list(student.col.find()))
# # student.update({'age': {'$eq': 18}}, {'age': 20}, False)
# student.delete({},False)
# print(list(student.find(onlyOne=False)))

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值