mongodb数据库怎么利用python进行连接

发布时间:2020-12-01 15:15:24 作者:Leah
来源:亿速云 阅读:140

本篇文章为大家展示了mongodb数据库怎么利用python进行连接,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

1、数据库配置类 MongoDBConn.py

#encoding=utf-8
'''

Mongo Conn连接类
'''

import pymongo

class DBConn:
  conn = None
  servers = "mongodb://localhost:27017"

  def connect(self):
    self.conn = pymongo.Connection(self.servers)

  def close(self):
    return self.conn.disconnect()

  def getConn(self):
    return self.conn

2、ngoDemo.py 类

#encoding=utf-8
'''

Mongo操作Demo
Done:
'''
import MongoDBConn

dbconn = MongoDBConn.DBConn()
conn = None
lifeba_users = None

def process():
  #建立连接
  dbconn.connect()
  global conn
  conn = dbconn.getConn()

  #列出server_info信息
  print conn.server_info()

  #列出全部数据库
  databases = conn.database_names()
  print databases

  #删除库和表
  dropTable()
  #添加数据库lifeba及表(collections)users
  createTable()
  #插入数据
  insertDatas()
  #更新数据
  updateData()
  #查询数据
  queryData()
  #删除数据
  deleteData()

  #释放连接
  dbconn.close()

def insertDatas():
  datas=[{"name":"steven1","realname":"测试1","age":25},
      {"name":"steven2","realname":"测试2","age":26},
      {"name":"steven1","realname":"测试3","age":23}]
  lifeba_users.insert(datas)

def updateData():
  '''只修改最后一条匹配到的数据
      第3个参数设置为True,没找到该数据就添加一条
      第4个参数设置为True,有多条记录就不更新
  '''
  lifeba_users.update({'name':'steven1'},{'$set':{'realname':'测试1修改'}}, False,False)

def deleteData():
  lifeba_users.remove({'name':'steven1'})

def queryData():
  #查询全部数据
  rows = lifeba_users.find()
  printResult(rows)
  #查询一个数据
  print lifeba_users.find_one()
  #带条件查询
  printResult(lifeba_users.find({'name':'steven2'}))
  printResult(lifeba_users.find({'name':{'$gt':25}}))

def createTable():
  '''创建库和表'''
  global lifeba_users
  lifeba_users = conn.lifeba.users

def dropTable():
  '''删除表'''
  global conn
  conn.drop_database("lifeba")

def printResult(rows):
  for row in rows:
    for key in row.keys():#遍历字典
      print row[key], #加, 不换行打印
    print ''

if __name__ == '__main__':
  process()

上述内容就是mongodb数据库怎么利用python进行连接,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. MongoDB数据库如何使用Pycharm进行连接
  2. 在idea中使用Java怎么对mongodb数据库进行连接

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python mongodb

上一篇:python爬虫多次请求出现超时如何解决

下一篇:利用python怎么将m4s缓存文件转换为MP4格式

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》