0%

Pyhton+MongoDB实现CRUD

1
# -*- coding:UTF-8 -*-#!/usr/bin/python"""@File    : mongodb.py@Time    : 2019/10/20 15:16@Author  : iBoy@Email   : iboy@iboy.tech@Software: PyCharm"""import pymongo# MONGO_URL = 'localhost'# MONGO_DB = 'taobao'# MONGO_TABLE = 'product'## client = pymongo.MongoClient(MONGO_URL)   # 创建一个连接对象# db = client[MONGO_DB]# 第一步,连接MongoDBclient=pymongo.MongoClient('mongodb://127.0.0.1:27017/')#   第二步,选择数据库或集合# 第二步,选择数据库或集合# db = client['test']db = client.test# 第一步,连接MongoDB# 选择好数据库后我们需要指定要操作的集合,与数据库的选择类似。tb=db.persons# p = db.persons    # persons集合# p = db['persons']#   第三步,添加数据person0={    'name':'杨豪',    'sex':'男'}person2 = {    'id':'00001',    'name':'Abc',    'age':19}person1 = {    'id':'00002',    'name':'Dfg',    'age':20}print(tb.insert_many([person0,person1,person2]))res = tb.find_one({'name':'Abc'})  # 查询 name 为 Abc 的人的信息,返回字典型的数据print(res)res = tb.find({'age':19})  # 查询集合中age是20的数据# res = p.find({'age':{'$gt':20}})  # 查询集合中age大于20的数据print(res)for r in res:    print(r)res = tb.find({'name':{'$regex':'^A.*'}})  # 查询集合中name以A开头的数据print(res)#where = {'name':'Abc'}res = tb.find_one(where)res['age'] = 25result = tb.update(where,res)  # 推荐使用 update_one() 或 update_many()print(result)#   我们通过PyMongo库里的MongoClient。其中第一个参数 host 是mongodb的地址,第二个参数是端口 port (不传参数的话默认是27017) result = tb.delete_one({'name':'Abc'})   # 删除名称为Abc的数据,推荐使用 delete_one() 和 delete_many(),执行后调用 result.delete_count,获得删除的数据条数print(result)# client = pymongo.MongoClient(host='127.0.0.1',port=27017)#   另一种方法是直接传递MongoDB的连接字符串,以 mongodb 开头。## client = pymongo.MongoClient('mongodb://127.0.0.1:27017/')#   第二步,选择数据库或集合##   在MongoDB中可以建立多个数据库,其中每个数据库又包含许多集合,类似于关系数据库中的表。选择数据库有两种方法,这两种方法作用相同。## db = client.test    # test数据库# db = client['test']#   选择好数据库后我们需要指定要操作的集合,与数据库的选择类似。## p = db.persons    # persons集合# p = db['persons']#   第三步,添加数据## 复制代码# person = {#     'id':'00001',#     'name':'Abc',#     'age':19# }# result = p.insert(person)# # 在PyMongo 3.x版本后,官方推荐使用insert_one(),该方法返回的不再是单纯的_id值,我们需要执行result.inserted_id查看 _id 值# print(result)
iBoy wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!