Python 操作MongoDB数据库


查看环境是否装有MongoDB pip list

同时需要下载对应的库

pip install pymongo

操作步骤

第一步连上数据库

#导入包
import pymongo
#建立链接  client 为自定义变量
client = pymongo.MongoClient()
#连远程数据库
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
#指定数据库
#db = client[数据库名]  例如之前已经创建的python64
my_db = client["python64"]
#指定集合 
#collection=db[集合名]  例如之前已经创建好的集合student  
my_collect = my_db["student"]

数据库操作集合

以下python3已经不推荐使用,也可以继续使用

#查找文档
find()
#添加文档
insert()
#修改文档
update()
#删除文档
remove()

推荐方法如下

新增文档

添加一条文档:insert _one

添加多条文档:insert _many

#新增一条数据
my_collect.insert_one({"_id":6,"name":"hanxin","age":24})
#新增多条数据
my_collect.insert_many([
    {"_id":7,"name":"joker","age":22},
    {"_id":8,"name":"xiaqi","age":26},
    {"_id":9,"name":"ajiu","age":19},
    {"_id":10,"name":"yuxuan","age":15},
])

查找文档

查找一条文档: find_one()

查找所有 find(),这是一个对象,可以利用for循环,遍历所有数据

#查询一条数据 如有有查询条件,在括号内加入条件即可,只会查找第一条符合条件的数据
result = my_collect.find_one()
print(result)
#my_collect.find()查询所有数据,返回的是一个地址,是一个可迭代对象
results = my_collect.find()
#循环遍历拿到所有的数据,如果有查询条件,也可以在括号内加入查询条件
for res in results:
    print(res)
#查找一条数据
results = my_collect.find({'name':'hansha'})
#查找find返回的是一个地址,需要遍历取值
my_collect.find_one({'name':'hansha'})

修改文档’’

修改一条文档:update_one()

修改多条文档:update_many()

#修改一条数据,将name = ajiu的年龄修改为18,只会修改一条
my_collect.update_one({"name":"ajiu"},{"$set":{"age":18}})
#修改多条数据
my_query = { "name": { "$regex": "^F" } }
new_values = { "$set": { "age": "18" } }
#将查找所有以 F 开头的 name 字段,并将查找到的所有数据中的age修改问为18
my_collect.update_many(my_query,new_values)

删除文档

修改一条文档: delete_one()

删除多条文档:delete_many()

#删除name=ajiu的文档(数据),删除会有返回值,返回值是一个地址
res = my_collect.delete_one({"name":"ajiu"})
#删除多条数据
my_query = { "name": { "$regex": "^F" } }
#删除所有 name 字段中以 F 开头的文档
res = my_collect.delete_many(my_query)
print(res.deleted_count,"个文档已删除")
#删除集合中的所有文档
#delete_many() 方法如果传入的是一个空的查询对象,则会删除集合中的所有文档:
res = my_collect.delete_many({})
print(res.deleted_count,"个文档已删除")

删除集合

我们可以使用 drop() 方法来删除一个集合。

#会删除student集合,删除成功返回true 删除失败返回false
my_collect.drop()

数据排序

sort() 方法可以指定升序或降序排序。

sort() 方法第一个参数为要排序的字段,第二个字段指定排序规则,1 为升序,-1 为降序,默认为升序。

#对字段age以升序方式排序
results = my_collect.find().sort("age")
for res in results:
    print(res)
#对字段age以降序方式排序
results = my_collect.find().sort("age",-1)
for res in results:
    print(res)

个人对mongo的简单封装

import pymongo
from databases import my_logger


class My_mongodb:
    def __init__(self,db_name,collect_name):
        try:
            self.log = my_logger.My_logger()
            self.my_client = pymongo.MongoClient()
            self.my_db = self.my_client[db_name]
            self.my_collent = self.my_db[collect_name]
        except Exception as e:
            self.log.use_Debug("数据库连接失败,错误内容:{}".format(e))
            # print("数据库连接失败!")
            # print(e)
        else:
            print("数据库连接成功!")

    #文档操作
    #新增数据
    def insert_data(self,argc,many = False):
        #插入多条数据
        if many:
            try:
                # print(argc)
                self.my_collent.insert_many(argc)
            except Exception as e:
                self.log.use_Debug("新增数据错误,错误内容:{}".format(e))
                # print("新增数据错误,错误内容%s",e)
            else:
                print("多条数据插入成功!")
        #插入单条数据
        else:
            try:
                # print(argc)
                self.my_collent.insert_one(argc)
            except Exception as e:
                self.log.use_Debug("新增数据错误,错误内容:{}".format(e))
            else:
                print("数据插入成功!")


    def find_data(self,argc = None,all = False):
        try:
            # 查找单条数据
            result = None
            if not all:
                # print(argc)
                result = self.my_collent.find_one(argc)
            #查找多条数据
            else:
                # print(argc)
                result = self.my_collent.find(argc)
        except Exception as e:
            self.log.use_Debug("查询数据错误,错误内容:{}".format(e))
            # print("查询数据错误,错误内容%s",e)
        else:
            if result != None:
                print("数据已找到!")
                if not all:
                    print(result)
                else:
                    for res in result:
                        print(res)
            else:
                print("数据未找到!")

    #修改数据
    def update_data(self,condition,new_data,many = False):
        try:
            if not many:
                #修改单条
                self.my_collent.update_one(condition,new_data)
            else:
                #修改多条
                self.my_collent.update_many(condition,new_data)
        except Exception as e:
            self.log.use_Debug("修改数据错误,错误内容:{}".format(e))
            # print("数据修改错误,错误内容%s",e)
        else:
            print("数据修改成功!")
            self.find_data(new_data.get('$set'))

    #删除数据
    def delete_data(self,condition,many=False):
        try:
            if not many:
                #删除单条
                result = self.my_collent.delete_one(condition)
            else:
                #删除多条
                result = self.my_collent.delete_many(condition)
        except Exception as e:
            self.log.use_Debug("删除数据错误,错误内容:{}".format(e))
            # print("数据删除错误,错误内容%s",e)
        else:
            print("数据删除成功!")
            print("{}个数据被删除!".format(result.deleted_count))

    #删除所有数据
    def delete_allData(self):
        self.my_collent.delete_many({})



if __name__ == '__main__':
    # print(1)
    mydb = My_mongodb('python64','student')
    data = '222'
    mydb.insert_data(data,many = True)
    mydb.delete_data('897')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python操作MongoDB数据库需要用到pymongo库,安装方法如下: ``` pip install pymongo ``` 连接数据库: ```python from pymongo import MongoClient # 连接MongoDB数据库 client = MongoClient('mongodb://localhost:27017/') ``` 通过client对象获取数据库和集合: ```python # 获取数据库对象 db = client.testdb # 获取集合对象(类似于关系数据库中的表) collection = db.test_collection ``` 插入数据: ```python # 插入一条数据 post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"]} collection.insert_one(post) # 插入多条数据 new_posts = [{"author": "Mike", "text": "Another post!", "tags": ["bulk", "insert"], "date": datetime.datetime(2009, 11, 12, 11, 14)}, {"author": "Eliot", "title": "MongoDB is fun", "text": "and pretty easy too!", "date": datetime.datetime(2009, 11, 10, 10, 45)}] collection.insert_many(new_posts) ``` 查询数据: ```python # 查询所有数据 for post in collection.find(): print(post) # 条件查询 query = {"author": "Mike"} for post in collection.find(query): print(post) # 正则表达式查询 query = {"author": {"$regex": "^M.*"}} for post in collection.find(query): print(post) ``` 修改数据: ```python # 更新一条数据 result = collection.update_one( {"author": "Mike"}, {"$set": {"text": "My first blog post (update)!"}} ) print("影响的文档数量:", result.modified_count) # 更新多条数据 result = collection.update_many( {"author": "Mike"}, {"$set": {"text": "My first blog post (update)!"}} ) print("影响的文档数量:", result.modified_count) ``` 删除数据: ```python # 删除一条数据 result = collection.delete_one({"author": "Mike"}) print("影响的文档数量:", result.deleted_count) # 删除多条数据 result = collection.delete_many({"author": "Mike"}) print("影响的文档数量:", result.deleted_count) # 删除所有数据 result = collection.delete_many({}) print("影响的文档数量:", result.deleted_count) ``` 关闭连接: ```python # 关闭连接 client.close() ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值