zoukankan      html  css  js  c++  java
  • 左手Mongodb右手Redis 通过python连接mongodb

    首先需要安装第三方包pymongo

    pip install pymongodb

     1 """
     2 通过python连接mongodb数据库
     3 首先需要初始化数据库连接
     4 """
     5 # 使用url统一资源标识符来指定链接地址
     6 # mongodb://username:password@ip:端口
     7 # 如果没有设定权限验证,则不需要密码
     8 # mongodb://ip:端口 ,默认端口27017 :http://localhost:27017/
     9 
    10 from pymongo import MongoClient
    11 
    12 # client = MongoClient("mongodb://localhost:27017")
    13 client = MongoClient(host="localhost", port=27017)
    14 # 指定数据库和集合名称
    15 db_name = "chapter_3"
    16 collection_name = 'example_data_1'
    17 # 数据库名
    18 database = client[db_name]
    19 # 相当于关系型数据库表名,表示数据库中的哪个表
    20 collection = database[collection_name]
    21 # 插入操作
    22 # collection.insert({'name': '王小六', 'age': 24, 'work': '厨师'})
    23 # 更新
    24 # collection.update({"name": "王小六"}, {"$set":{"address": "重庆"}})
    25 # 查询操作
    26 # rows = collection.find({}, {"_id": 0})
    27 rows = collection.find({})
    28 for row in rows:
    29     # print(row['name'])
    30     print(row)
    31 # 删除name = 18030.0
    32 # 先查询,后删除
    33 # result = collection.delete_one({"name": 18030})
    34 result = collection.find({"name": 18030})
    35 print(type(result))
    36 # upsert更新插入
    37 # 如果有数据,则更新,否则插入
    38 # 在python中,不存在为None,在mongodb,不存在为null.
    39 # db.getCollection('example_data_1').find({"work":null})
    40 results = collection.find({"work": None})
    41 for result in results:
    42     print(result)
  • 相关阅读:
    如何成为强大的程序员?(转)
    PHP Directory 函数
    PHP 类相关函数
    myeclipse安装svn插件的多种方式
    PHPEXCEL类操作EXCEL
    PHP 自定义错误处理函数(转)
    JBoss JBPM 实践系列(一) 安装配置(Tomcat 6.0 + MySQL 5.1)
    Ext.data.Store的相关知识
    Lotus Notes 和 Crystal Report 的整合應用
    JBoss JBPM 实践系列(二) jbpm设计器的配置和使用
  • 原文地址:https://www.cnblogs.com/hamish26/p/11357072.html
Copyright © 2011-2022 走看看