python 使用mongdb数据库

超级简单!!

Mongdb数据库是基于分布式文件存储的数据库。

跟Mysql不一样,更利于保存json,文档数组之类,比如存入 Mysql对象还要进行序列化。

这篇博客只是简单的增删改查适合萌新,如果你已经会了的大佬可以看别的啦。

环境是Mac环境,代码通用。

一、安装数据库

 使用brew安装就可以啦,中间你的电脑brew如果可能需要更新会出现小问题。但是仔细看log一般,shell里面会有提示,直接复制运行把error搞定就可以啦。

brew tap mongodb/brew 

brew install mongodb-community@4.4  #安装4.4版本

brew services start mongodb-community@4.4 #启动

brew services stop mongodb-community@4.4 #关闭

启动成功就是这个样子 

二、安装studio 3t 数据库可视化工具 

官网地址:https://robomongo.org/download 

windows可以官网下载,我把mac版本上传到网盘了地址 

链接:https://pan.baidu.com/s/1uA_vdCjc4zhnhQ1BBqSV6Q  密码:ejx5

创建数据库等会我们要用到的

第二步之后弹出下面页面👇,输入名称点save就好了。就创建成功了

 三、增删改查代码

使用pymongo,没有的需要先安装命令行,清华镜像源安装。

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pymongodb
import pymongo

# 创建mongodb连接,不传端口默认27017
client = pymongo.MongoClient(host='localhost', port=27017)
db = client['test']  # 指定数据库


class MongodbHelp:
    def __init__(self):
        global db
        self.collection = db.student  # 指定集合

    # 插入一条数据
    def insert_student_on(self):
        student = {
            'id': '1',
            'name': '赵雷',
            'age': 18,
        }
        result = self.collection.insert_one(student)
        print(result)

    # 多条数据插入
    def insert_student_many(self):
        student = {
            'id': '4',
            'name': 'saliy',
            'age': 25,
        }
        student2 = {
            'id': '5',
            'name': 'Lean',
            'age': 34,
        }
        result = self.collection.insert_many([student, student2])
        print(result)

    # 查询数据
    def select_student(self):
        # 查询age大于10的数据  $gt代表大于
        results = self.collection.find({'age': {'$gt': 10}})
        for result in results:
            print(result)

    # 使用正则表达式查找数据
    def select_student_re(self):
        # name开头是L开头
        results = self.collection.find({'name': {'$regex': '^L.*'}})
        print(results)
        count = self.collection.count()
        print("Mongodb共有数据:{count}".format(count=count))

    # 数据排序
    def select_student_sort(self):
        # DESCENDING 降序  ASCENDING升序
        resluts = self.collection.find().sort('age', pymongo.ASCENDING)
        for result in resluts:
            print("降序排序:", result['age'], result['name'])

    # 修改单条数据
    def update_student(self):
        condition = {
            'name': 'Leo'
        }
        # 查找名称为leo姓名单个数据
        student = self.collection.find_one(condition)
        student['age'] = 33
        # 查找出来student更改数据,像是java中list get出数据然后修改
        result = self.collection.update_one(condition, {'$set': student})
        print(result)

    # 更改多条数据
    def update_student_many(self):
        # 大于20岁年龄全部加一
        condition = {'age': {'$gt': 20}}
        result = self.collection.update_many(condition, {'$inc': {'age': 1}})
        print(result)

    # 删除年龄小于20的数据
    def delete_student(self):
        condition = {'age': {'$lt': 20}}
        self.collection.delete_many(condition)


if __name__ == "__main__":
    #monggo = MongodbHelp()
    #monggo.select_student_sort()
    #monggo.delete_student()
    #monggo.select_student()
    # monggo.insert_student_many()
    # monggo.select_student()
    # monggo.select_student_re()
    # monggo.insert_student_on()
    # monggo.insert_student_many()

根据上面命令就可以在数据库中查询了

符号归纳

$lt   小于   {'age':{'$lt':20}}

$gt  大于  {'age':{'$gt':20}}

$lte  小于等于  {'age':{'$lte':20}}

$gte 大于等于 {'age':{'$gte':20}}

$ne 不等于 {'age':{'$ne':20}}

$in 在范围内 {'age':{'$in':20}}

$nin 不在范围内 {'age':{'$nin':20}}

四、总结 

  1. 多个条件查询容易写错例如 {'age':{'$lt':20}},容易把冒号写成逗号。
  2. 符号归纳较多易记混,还有些符号没有写上去,还需要查询 $inc

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值