python实现mongodb的增删改查

发布时间:2019-08-28 09:11:06编辑:auto阅读(1523)


                                                          python实现mongodb的增删改查


    环境:

    192.168.122.1    python

    192.168.122.11  mongodb


    一、安装pip,python的管理工具

    官网下载: pip-18.0 

    Screenshot from 2018-08-12 20-00-55.png


    安装pip

    [root@foundation12 pip-18.0]# python setup.py install

    如下,安装成功

    注:在安装pip时,下载setuptools-39.2.0.zip 解压并运行python setup.py install ,否则后面安装会有错误;


    二、python连接mongodb

    Python使用pymongo模块实现连接mongodb

    安装PyMongo

    pip install pymongo

    Screenshot from 2018-08-12 22-51-09.png


    三、安装python  IDE工具

    官网下载  pycharm-community-2018.2.1.tar.gz

    解压到指定目录下,我指定为 /usr/local/

    在/bin目录下 ./pycharm.sh 开启即可;


    Screenshot from 2018-08-13 10-22-53.png

    注:在使用pycharm时,需要手动添加模块

    file --> setting --> project interpreter  点击加号,搜索安装即可(退出:上方右键  close)


    Screenshot from 2018-08-13 10-26-34.png


    四、python连接操作mongodb


    Screenshot from 2018-08-13 10-35-38.png

    import pymongo         //导入模块

    from pymongo import MongoClient

    client= MongoClient('192.168.122.11', 27017)    //链接数据库主机

    db = client.lh                    //连接lh数据库,没有则自动创建

    my_set = db.test_set        //使用test_set集合,没有则自动创建

    my_set.insert({"name":"zhangsan","age":18})   //插入数据 


    验证,在mongodb服务器查看

    如下,创建了库,集合,插入了数据 

    Screenshot from 2018-08-13 09-40-03.png


    如下,添加多条数据

    users = [{"name":"lisi","age":20},{"name":"wangwu","age":23}]
    my_set.insert(users)

    查看

    Screenshot from 2018-08-13 10-43-15.png

    注:每运行一次,就会添加,并且不会覆盖之前添加的数据(如:zhangsan)


    用update去更新数据

    my_set.update({"name":"zhangsan"},{'$set':{"age":22}})

    Screenshot from 2018-08-13 11-00-00.png

    查看:

    默认改变第一个张三的age;


    Screenshot from 2018-08-13 11-00-27.png


    (1)查询全部

    for i in my_set.find():    

        print(i)

    Screenshot from 2018-08-13 11-02-22.png

    Screenshot from 2018-08-13 11-02-29.png

    (2)查询name=zhangsan的

    for i in my_set.find({"name":"zhangsan"}):
        print(i)

    Screenshot from 2018-08-13 11-04-22.png

    Screenshot from 2018-08-13 11-04-28.png


    print(my_set.find_one({"name":"zhangsan"}))

    Screenshot from 2018-08-13 11-06-09.png

    Screenshot from 2018-08-13 11-06-16.png


    条件查询

    查询集合中age大于25的所有记录

    for i in my_set.find({"age":{"$gt":20}}):    

        print(i)

    Screenshot from 2018-08-13 11-36-41.png

    Screenshot from 2018-08-13 12-12-16.png


    删除name=lisi的全部记录

    my_set.remove({'name': 'lisi'})

    Screenshot from 2018-08-13 11-08-18.png

    如下:lisi数据删除

    Screenshot from 2018-08-13 11-08-36.png


    删除name=zhangsan 的某个id的记录

    id = my_set.find_one({"name":"zhangsan"})["_id"]
    my_set.remove(id)

    Screenshot from 2018-08-13 11-10-05.png

    Screenshot from 2018-08-13 11-10-34.png


关键字