Python编程:mongodb的基本增删改查操作

简介: Python编程:mongodb的基本增删改查操作

文档:http://api.mongodb.com/python/current/api/index.html


第一步当然是配置环境,启动数据库服务


mongodb的安装及简单使用-mac环境


引入模块

# -*- coding: utf-8 -*-
# @File    : pymongo_demo.py
# @Date    : 2018-06-02
# @Author  : Peng Shiyu
import pymongo

1、创建MongoDB的连接对象

# client = pymongo.MongoClient(host="localhost", port=27017)
client = pymongo.MongoClient('mongodb://localhost:27017/')

2、指定数据库

# db = client["mydemo"]
db = client.mydemo

3、指定集合Collection对象

# collection = db["students"]
collection = db.students

4、插入数据

# 一条数据
student = {
    'id': '20170101',
    'name': '小明',
    'age': 22,
    'gender': '男性'
}
# result = collection.insert(student)
result = collection.insert_one(student)
print(result)  # <pymongo.results.InsertOneResult object at 0x1034e08c8>
print(result.inserted_id)  # 5b1205b2d7696c4230dd9456
# 多条数据
student1 = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}
student2 = {
    'id': '20170202',
    'name': 'Mike',
    'age': 21,
    'gender': 'male'
}
#
# # result = collection.insert([student1, student2])
result = collection.insert_many([student1, student2])
print(result)  # <pymongo.results.InsertManyResult object at 0x1034e0748>
print(result.inserted_ids)
# # [ObjectId('5b1205b2d7696c4230dd9457'), ObjectId('5b1205b2d7696c4230dd9458')]

5、查询数据库

# 查询一条数据
result = collection.find_one({"name": "Mike"})
print(type(result))  # <class 'dict'>
print(result)
# {'_id': ObjectId('5b1204a3d7696c41c083d21e'),
# 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
# 通过_id属性来查询, 不存在则返回None
from bson.objectid import ObjectId
result = collection.find_one({'_id': ObjectId('5b1204a3d7696c41c083d21e')})
print(result)
# {'_id': ObjectId('5b1204a3d7696c41c083d21e'),
# 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
# 查询多条数据, 返回一个生成器
results = collection.find({"age": 21})
print(results)  # <pymongo.cursor.Cursor object at 0x10133f160>
for result in results:
    print(result)
# {'_id': ObjectId('5b12055fd7696c4208deb74a'), 
# 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
# 条件查询
results = collection.find({"age": {"$gt": 20}})
for result in results:
    print(result)
# {'_id': ObjectId('5b1209ccd7696c437c51d5bb'), 
# 'id': '20170101', 'name': '小明', 'age': 22, 'gender': '男性'}
# {'_id': ObjectId('5b1209ccd7696c437c51d5bd'), 
# 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
# 正则匹配查询
results = collection.find({"name": {"$regex": "^M.*"}})
for result in results:
    print(result)
# {'_id': ObjectId('5b1209ccd7696c437c51d5bd'),
# 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
## 转为list
>>> db.collection.find()
<pymongo.cursor.Cursor object at 0x108dabf50>
>>> list(db.collection.find())
[
  {'_id': ObjectId('5839b12eee86fb71849a0905'), 'name': 'Tom'}
]

比较符号

image.png


说明:

lt: less than

gt: great than

e: equal


功能符号

image.png


image.png

6、查询计数

count = collection.find().count()
print(count)  # 3

7、数据排序

# 升序pymongo.ASCENDING 降序pymongo.DESCENDING
results = collection.find().sort("name", pymongo.ASCENDING)
print([result["name"] for result in results])
# ['Jordan', 'Mike', '小明']

8、数据的偏移

results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])
# ['小明']
results = collection.find().sort('name', pymongo.ASCENDING).skip(1).limit(1)
print([result['name'] for result in results])
# ['Mike']
# 数据库数量非常庞大的时候,不要使用大的偏移量
from bson.objectid import ObjectId
results = collection.find({'_id': {'$gt': ObjectId('5b1209ccd7696c437c51d5bb')}})
print([result['name'] for result in results])

9、更新数据库

更新函数

update_one(filter, update, upsert=False, 
bypass_document_validation=False, collation=None, array_filters=None, session=None)
update_many(filter, update, upsert=False, 
array_filters=None, bypass_document_validation=False, collation=None, session=None)
# 过时了 
update(spec, document, upsert=False, 
manipulate=False, multi=False, check_keys=True, **kwargs)
condition = {'name': 'Mike'}
student = collection.find_one(condition)
student['age'] = 25
# 全部用student字典替换
# result = collection.update(condition, student)
# 只更新student字典内存在的字段
result = collection.update(condition, {'$set': student})
print(result)
# {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}
condition = {'name': 'Mike'}
student = collection.find_one(condition)
student['age'] = 26
result = collection.update_one(condition, {'$set': student})
print(result)
# <pymongo.results.UpdateResult object at 0x1034de708>
print(result.matched_count, result.modified_count)
# 1 1
condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
# <pymongo.results.UpdateResult object at 0x1034e8588>
print(result.matched_count, result.modified_count)
# 1 1

10、数据删除

result = collection.remove({'name': 'Jordan'})
print(result)
# 删除一条
result = collection.delete_one({'name': 'Kevin'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age': {'$lt': 25}})
print(result.deleted_count)
# 删除多条
result = collection.delete_many({'name': 'Kevin'})

官方文档:

http://api.mongodb.com/python/current/api/pymongo/collection.html


多条件查询


db.getCollection('table').find({"$and": [{"detail": {"$ne": null}}, {"detail": {"$ne": true}}]})


相关文章
|
3月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
319 102
|
3月前
|
数据采集 机器学习/深度学习 算法框架/工具
Python:现代编程的瑞士军刀
Python:现代编程的瑞士军刀
346 104
|
3月前
|
人工智能 自然语言处理 算法框架/工具
Python:现代编程的首选语言
Python:现代编程的首选语言
276 103
|
3月前
|
机器学习/深度学习 人工智能 数据挖掘
Python:现代编程的首选语言
Python:现代编程的首选语言
206 82
|
2月前
|
Python
Python编程:运算符详解
本文全面详解Python各类运算符,涵盖算术、比较、逻辑、赋值、位、身份、成员运算符及优先级规则,结合实例代码与运行结果,助你深入掌握Python运算符的使用方法与应用场景。
219 3
|
2月前
|
数据处理 Python
Python编程:类型转换与输入输出
本教程介绍Python中输入输出与类型转换的基础知识,涵盖input()和print()的使用,int()、float()等类型转换方法,并通过综合示例演示数据处理、错误处理及格式化输出,助你掌握核心编程技能。
483 3
|
2月前
|
并行计算 安全 计算机视觉
Python多进程编程:用multiprocessing突破GIL限制
Python中GIL限制多线程性能,尤其在CPU密集型任务中。`multiprocessing`模块通过创建独立进程,绕过GIL,实现真正的并行计算。它支持进程池、队列、管道、共享内存和同步机制,适用于科学计算、图像处理等场景。相比多线程,多进程更适合利用多核优势,虽有较高内存开销,但能显著提升性能。合理使用进程池与通信机制,可最大化效率。
301 3
|
2月前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
312 0
|
9月前
|
NoSQL MongoDB 微服务
微服务——MongoDB实战演练——文章评论的基本增删改查
本节介绍了文章评论的基本增删改查功能实现。首先,在`cn.itcast.article.dao`包下创建数据访问接口`CommentRepository`,继承`MongoRepository`以支持MongoDB操作。接着,在`cn.itcast.article.service`包下创建业务逻辑类`CommentService`,通过注入`CommentRepository`实现保存、更新、删除及查询评论的功能。最后,新建Junit测试类`CommentServiceTest`,对保存和查询功能进行测试,并展示测试结果截图,验证功能的正确性。
219 2
|
3月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的多面手
Python:现代编程的多面手
93 0