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

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介: 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'}
]

比较符号

符号

表示

含义

示例

:

=

等于

{“age”: 20}

$lt

<

小于

{“age”: {"$lt": 20}}

$gt

>

大于

{“age”: {"$gt": 20}}

$lte

<=

小于等于

{“age”: {"$lte": 20}}

$gte

>=

大于等于

{“age”: {"$gte": 20}}

$ne

!=

不等于

{“age”: {"$ne": 20}}

$in

in

范围内

{“age”: {"$in": [20, 30]}}

$nin

not in

不在范围内

{“age”: {"$nin": [20, 30]}}

 

 

 


说明:

lt: less than

gt: great than

e: equal

功能符号

符号

含义

示例

示例说明

$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

高级条件查询

{“name”: {"$where": “obj.age==obj.count”}}

自身年龄等于自身数量


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}}]})

参考:

菜鸟用Python操作MongoDB,看这一篇就够了

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
相关文章
|
4月前
|
NoSQL MongoDB Python
深入了解 Python MongoDB 操作:排序、删除、更新、结果限制全面解析
使用 sort() 方法对结果进行升序或降序排序。 sort() 方法接受一个参数用于“字段名”,一个参数用于“方向”(升序是默认方向)。
70 0
|
6月前
|
NoSQL MongoDB 数据库
23 MongoDB高级 - 与python交互
23 MongoDB高级 - 与python交互
30 0
|
7月前
|
存储 NoSQL MongoDB
Python使用MongoDB数据库
Python使用MongoDB数据库
|
6月前
|
NoSQL MongoDB Python
python mongodb pymongo 连接 身份认证
python mongodb pymongo 连接 身份认证
66 0
|
4月前
|
NoSQL 关系型数据库 MySQL
深入了解 Python MongoDB 查询:find 和 find_one 方法完全解析
在 MongoDB 中,我们使用 find() 和 find_one() 方法来在集合中查找数据,就像在MySQL数据库中使用 SELECT 语句来在表中查找数据一样
67 1
|
19天前
|
NoSQL MongoDB Redis
Python与NoSQL数据库(MongoDB、Redis等)面试问答
【4月更文挑战第16天】本文探讨了Python与NoSQL数据库(如MongoDB、Redis)在面试中的常见问题,包括连接与操作数据库、错误处理、高级特性和缓存策略。重点介绍了使用`pymongo`和`redis`库进行CRUD操作、异常捕获以及数据一致性管理。通过理解这些问题、易错点及避免策略,并结合代码示例,开发者能在面试中展现其技术实力和实践经验。
276 8
Python与NoSQL数据库(MongoDB、Redis等)面试问答
|
4月前
|
存储 NoSQL MongoDB
学习如何使用 Python 连接 MongoDB: PyMongo 安装和基础操作教程
Python 需要一个 MongoDB 驱动程序来访问 MongoDB 数据库。我将使用 MongoDB 驱动程序 PyMongo 建议您使用 PIP 来安装 PyMongo。PIP 很可能已经安装在您的 Python 环境中。将命令行导航到 PIP 的位置,然后键入以下内容:
98 1
|
4月前
|
存储 NoSQL MongoDB
Python小姿势 - Python操作MongoDB数据库
Python小姿势 - Python操作MongoDB数据库
|
10月前
|
NoSQL 关系型数据库 MySQL
Python MongoDB复习第一章(二)
Python MongoDB复习第一章(二)
55 0
|
10月前
|
SQL 存储 JSON
Python MongoDB复习第一章(一)
Python MongoDB复习第一章(一)
67 0