首页 > 数据库 >pymongo:Python下 MongoDB 的存储操作

pymongo:Python下 MongoDB 的存储操作

时间:2024-05-08 15:22:49浏览次数:11  
标签:name Python MongoDB age db collection result print pymongo

1.连接mongodb

#########  方法一  ##########
import pymongo
# MongoClient()返回一个mongodb的连接对象client
client = pymongo.MongoClient(host="localhost",port=27017)

#########  方法二  ##########
import pymongo
# MongoClient的第一个参数host还可以直接传MongoDB的连接字符串,以mongodb开头
client = pymongo.MongoClient(host="mongodb://127.0.0.1:27017/")

2.指定数据库

######  方法一  ######
# 指定test数据库
db = client.test

######  方法二  ######
# 指定test数据库(调用client的test属性即可返回test数据库)
db = client["test"]

3.指定集合

######  方法一  ######
# 指定student集合
collection = db.student

######  方法二  ######
# 指定student集合
collection = db["student"]

4.插入数据

  • db.collection.insert()
    可以插入一条数据(dict),也可以插入多条数据(list),返回‘_id’或‘_id’的集合
###### 插入一条数据 ######
student = {
 'name': 'Jordan',
 'age': 18,
 'gender': 'man'
}

result = db.collection.insert(student)
# insert()返回执行后文档的主键'_id'的值
print(result)  # 5932a68615c2606814c91f3d

######  插入多条数据  ######
student1 = {
 'name': 'Jordan',
 'age': 10,
 'gender': 'man'
}

student2 = {
 'name': 'Mike',
 'age': 11,
 'gender': 'man'
}

result = collection.insert([student1,student2])
# insert()返回执行后文档的主键'_id'的集合
print(result)  #[ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]

pymongo 3.x版本中,insert()方法官方已不推荐使用,推荐使用insert_one()insert_many()将插入单条和多条记录分开。

  • db.collection.insert_one()
    用于插入单条记录,返回的是InsertOneResult对象
student = {
 'name': 'Jordan',
 'age': 18,
 'gender': 'man'
}

result = collection.insert_one(student)
# insert_one()返回的是InsertOneResult对象,我们可以调用其inserted_id属性获取_id。
print(result)  # <pymongo.results.InsertOneResult object at 0x10d68b558>
print(result.inserted_id) # 5932ab0f15c2606f0c1cf6c5
  • db.collection.insert_many()
    用于插入多条记录,返回的是InsertManyResult对象

student1 = {
 'name': 'Jordan',
 'age': 10,
 'gender': 'man'
}

student2 = {
 'name': 'Mike',
 'age': 11,
 'gender': 'man'
}

result = collection.insert_many([student1, student2])
# insert_many()方法返回的类型是InsertManyResult,调用inserted_ids属性可以获取插入数据的_id列表
print(result)  # <pymongo.results.InsertManyResult object at 0x101dea558>
print(result.inserted_ids) # [ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]

5.查询数据:find_one()、find()

  • db.collection.find_one()
    查询返回单个结果(dict或者None)
result = db.collection.find_one({"name": "Mike"})
print(result) #{'_id': ObjectId('5932a80115c2606a59e8a049'),'name': 'Mike', 'age': 21, 'gende' :'man'}
  • db.collection.find()
    查询返回多个结果(cursor类型,可迭代)。
results = collection.find({"age":18})
print(results) # <pymongo.cursor.Cursor object at 0x1032d5128>
for result in results:
      print(result)
#

如果要查询年龄大于 20 的数据,则写法如下:

results = collection.find({'age': {'$gt': 20}})

比较符号:

符  号 含  义 示  例
$lt 小于 {'age': {'$lt': 20}}
$gt 大于 {'age': {'$gt': 20}}
$lte 小于等于 {'age': {'$lte': 20}}
$gte 大于等于 {'age': {'$gte': 20}}
$ne 不等于 {'age': {'$ne': 20}}
$in 在范围内 {'age': {'$in': [20, 23]}}
$nin 不在范围内 {'age': {'$nin': [20, 23]}}

另外,还可以进行正则匹配查询。例如,查询名字以 M 开头的学生数据,示例如下:

results = collection.find({'name': {'$regex': '^M.*'}})

这里使用 $regex 来指定正则匹配,^M.* 代表以 M 开头的正则表达式。

这里将一些功能符号再归类为下表。

符  号 含  义 示  例 示例含义
$regex 匹配正则表达式 {'name': {'$regex': '^M.*'}} name
以 M 开头
$exists 属性是否存在 {'name': {'$exists': True}} name
属性存在
$type 类型判断 {'age': {'$type': 'int'}} age
的类型为 int
$mod 数字模操作 {'age': {'$mod': [5, 0]}} 年龄模 5 余 0
$text 文本查询 {'$text': {'$search': 'Mike'}} text
类型的属性中包含 Mike
字符串
$where 高级条件查询 {'$where': 'obj.fans_count == obj.follows_count'} 自身粉丝数等于关注数

关于这些操作的更详细用法,可以在 MongoDB 官方文档找到: https://docs.mongodb.com/manual/reference/operator/query/

  • 多条件查询 **$and** **$or**
# and查询
db.collection.find({
         $and :  [
                { "age" :  {$gt : 10 }} ,
                { "gender" :  "man" }
          ]
})

#or查询
db.collection.find({
          $or : [
                    {"age" :  {$gt : 10 }},
                    { "gender" :  "man"}
         ]
})

#and查询 和 or查询
db.inventory.find( {
    $and : [
        { $or : [ { price : 0.99 }, { price : 1.99 } ] },
        { $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
    ]
} )
  • count()
    计数,对查询结果进行个数统计
count = collection.find().count()
print(count)
  • 排序 **sort()**
    调用sort方法,传入要排序的字段and升降序标志即可
#单列升序排列
results = db.collection.find().sort('name', pymongo.ASCENDING) # 升序(默认)
print([result['name'] for result in results])

# 单列降序排列
results = db.collection.find().sort("name",pymongo.DESCENDING)  #降序
print([result['name'] for result in results])

#多列排序
results = db.collection.find().sort([
  ("name", pymongo.ASCENDING),("age", pymongo.DESCENDING)
])
  • 偏移 **skip()**
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])

注意:在数据量非常庞大时(千万、亿级别),最好不要用skip()来查询数据,可能导致内存溢出。可以使用
find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}})
这样的方法来查询。

  • 限制 **limit()**
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
print([result['name'] for result in results])

6.更新数据

  • db.collection.update()
    修改单条或者多条文档,已不推荐此用法
result = collection.update(
            {"age": {"$lt" : 15}} ,
            {"$set" : {"gender" : "woman"}}
)

print(result)  # {'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}
  • db.collection.update_one()
    修改单条文档,返回结果是UpdateResult类型

针对UpdateResult类型数据,可以调用matched_count和modified_count属性分别获取匹配的条数和影响的条数

result = db.collection.update_one(
              {"name" : "Mike"} ,
              {
                "$inc" : {"age" : 5},
                "$set": {"gender": "male"}
              }
)

print(result)   # <pymongo.results.UpdateResult object at 0x10d17b678>

print(result.matched_count, result.modified_count)   # 1  1
  • db.collection.update_many()
    修改多条文档,返回结果是UpdateResult类型
result = db.collection.update_many(
              {"name" : "Mike"} ,
              {"$inc" : {"age" : 5}}
)

print(result)   # <pymongo.results.UpdateResult object at 0x10c6384c8>

print(result.matched_count, result.modified_count)   # 3   3

7.删除数据

  • db.collection.remove()
    删除指定条件的所有数据
result = db.collection.remove({"age" : {"$gte" : 10}})

print(result)  # {'ok': 3, 'n': 3}
  • db.collection.delete_one()
    删除第一条符合条件的数据,返回DeleteResult类型数据
result = collection.delete_one({'name': 'Kevin'})
print(result) # <pymongo.results.DeleteResult object at 0x10e6ba4c8>
print(result.deleted_count)  # 1
  • db.collection.delete_many()
    删除所有符合条件的数据,返回DeleteResult类型数据
result = collection.delete_many({'name': 'Kevin'})
print(result) # <pymongo.results.DeleteResult object at 0x55e6be5f1>
print(result.deleted_count)  # 4

其他

另外,pymongo还提供了更多方法,如find_one_and_delete() find_one_and_replace() find_one_and_update()
当然,还有操作索引的方法:create_index() create_indexes() drop_index()等。

import pymongo

client = pymongo.MongoClient(host="127.0.0.1", port="27017")

db = client["test"]
coll = db["myindex"]

# 在后台创建唯一索引
coll.create_index([(x,1)], unique = True, background = True,name = "x_1")

# 查看集合coll的所有索引信息
result = coll.index_information()
print(result)

# 在后台创建复合索引
db.myindex.create_index([("x", 1), ("y", 1)])

# 删除索引
coll.drop_index([("x", 1)])
# coll.drop_index("x_1")

详细用法可以参见官方文档:http://api.mongodb.com/python/current/api/pymongo/collection.html

另外还有对数据库、集合本身以及其他的一些操作,在这不再一一讲解,可以参见官方文档:http://api.mongodb.com/python/current/api/pymongo/

标签:name,Python,MongoDB,age,db,collection,result,print,pymongo
From: https://www.cnblogs.com/luckzack/p/18179906

相关文章

  • struct:Python二进制数据结构
    在C/C++语言中,struct被称为结构体。而在Python中,struct是一个专门的库,用于处理字节串与原生Python数据结构类型之间的转换。本篇,将详细介绍二进制数据结构struct的使用方式。函数与Struct类struct库包含了一组处理结构值得模块级函数,以及一个Struct类。格式指示符将由字符串格......
  • NumPy:Python科学计算基础包
    NumPy是Python科学计算的基础包,几乎所有用Python工作的科学家都利用了的强大功能。此外,它也广泛应用在开源的项目中,如:Pandas、Seaborn、Matplotlib、scikit-learn等。Numpy全称NumericalPython。它提供了2种基本的对象:ndarray与ufunc。ndarray是存储单一数据的多维数组,它......
  • python写入文件
    importjsonimportosimportrandomimporttimefromopenpyxlimportload_workbookimportrequestsfromopenpyxlimportWorkbookurl='https://www.picchealth.com/eportal/ui?moduleId=9bd0917443454517a791cc11fdaddfae&struts.portlet.action=/portle......
  • Python解释器和Pycharm的安装
    Python解释器和Pycharm的安装【一】Python解释器安裝(windows)【1】进入Python官网https://www.python.org【2】选择Windows系统【3】选择解释器版本3.10.11【4】安装解释器(1)双击安装程序选择最下面的选项(2)选择安装包管理工具全部勾上(3)选择安装位置全部勾......
  • python常用重试工具tenacity
    安装tenacitypipinstalltenacity使用示例fromtenacityimportretry,wait_fixed,stop_after_attempt​​@retry(stop=stop_after_attempt(5),wait=wait_fixed(0.2),reraise=True)deftest(): pass​​#上面的重试装饰器表示:最多重试5次,每次间隔时间0.2,当重试次......
  • 编程语言和Python语言介绍
    编程语言和Python语言介绍一、【编程语言介绍】【1】机器语言(1)机器语言是什么机器语言就是计算机可以理解的语言,可以直接通过机器语言操作我们的硬件计算机是基于电工作的,高频是0,低频是1计算机通过控制高低频变化来工作(2)机器指令通过制高低电频的变化组成一系列的指令......
  • [转]Linux安装conda(python的版本管理工具)
    原文地址:Linux安装conda-知乎Conda的安装与使用在服务器上使用Linux命令行安装Conda(Conda可以理解类似于应用商店或是mac里的AappStore。可以在conda里面安装软件,或者在conda之外安装),使用conda管理小环境和使用conda管理软件,用conda来安装和管理生信软件以及环境比较方便。......
  • python logger 打印日志错误行数
    pythonlogger打印日志错误行数importloggingapp=Flask(__name__)#配置日志handler=logging.FileHandler('app.log')#日志输出到文件handler.setLevel(logging.INFO)#设置日志级别formatter=logging.Formatter('%(asctime)s-%(name)s-%(levelname)......
  • python教程6.4-excel处理模块
    第三方开源模块安装 创建文件打开已有文件写数据选择表保存表遍历表按行遍历按列遍历遍历指定行列遍历指定第几列数据删除表设置单元格样式字体对齐设置行高列宽 ......
  • python+selenium+excel自动登录,自动填写网页
    经常有些网页要登录,然后频繁填写一些重复的内容,本文暂只考虑不需要验证码的情况,可以通过selenium模拟用户行为在页面操作,用excel拖出相似内容,用xlrd读取并填写到网页中。导入相关包fromseleniumimportwebdriverimportosimportxlrdimportxlwtimportjsonimportreq......