Sort:  

PyMongo 是一个包含 MongoDB 操作工具的 Python 发行版,也是从 Python 访问 MongoDB 的推荐方式。

uv add pymongo # 4.19.0
# pip install pymongo  
# pip install --upgrade pymongo


from pymongo import MongoClient

# 方式一:连接本地
client = MongoClient("mongodb://localhost:27017")

# 方式二:带认证的远程连接
client = MongoClient("mongodb://user:password@host:27017/mydb?authSource=admin")
Loading...

在 Web 应用程序中,一个常见的任务是从请求 URL 中获取 ObjectId 并查找匹配的文档。在这种情况下,在将 ObjectId 传递给 find_one 之前,必须先将其从字符串转换为对象。按 _id 查询要先转 ObjectId。

from bson import ObjectId

doc = collection.find_one({"_id": ObjectId("690123456789abcdef012345")})
# 错误写法:find_one({"_id": "690123456789abcdef012345"})  # 字符串匹配不到 ObjectId

# The web framework gets post_id from the URL and passes it as a string
def get(post_id):
    # Convert from string to ObjectId:
    document = client.db.collection.find_one({'_id': ObjectId(post_id)})

操作MongoDB

#查找所有数据
db.集合名.find()
# 查找到所有匹配数据
db.集合名.find({条件文档})
# 只返回匹配的第一个数据
db.stu.find({age:{$gt:16}}) #查询年龄大于16的记录
db.stu.find({$or:[{age:{$gt:18}},{name:"xiaoming"}]) #查询年龄大于18或者名字是xiaoming的记录
#使用$where后面写一个函数,返回满足条件的数据
db.stu.find({$where:function(){return this.age>20}})
#用于读取指定数量的文档
db.集合名称.find().limit(NUMBER)
#对查询结果排序(参数1升序,参数-1降序)
db.集合名称.find().sort({字段:1,...}) 
#统计结果中的文档数
db.集合名称.find({条件}).count()

参考

添加索引可以帮助加快某些查询的速度,还可以为查询和存储文档添加额外的功能。在本示例中,我们将演示如何为一个键创建唯一索引,该索引将拒绝那些重复的键值。

collection.create_index("name")                    # 普通索引
collection.create_index([("age", -1)], unique=False)  # 降序索引
collection.create_index("email", unique=True)      # 唯一索引

# 为文档创建索引字段,为唯一值,可加快查询速度等
# 该索引会阻止我们插入用户_id 已在集合中的文档
result = collection.create_index([("user_id", pymongo.ASCENDING)], unique=True)
sorted(list(collection.index_information()))
['_id_', 'user_id_1']
# 请注意,我们现在有两个索引:一个是 MongoDB 自动创建的 _id 索引,另一个是我们刚刚创建的 user_id 索引。

user_profiles = [{"user_id": 211, "name": "Luke"}, {"user_id": 212, "name": "Ziltoid"}]
new_profile = {"user_id": 213, "name": "Drew"}
duplicate_profile = {"user_id": 212, "name": "Tommy"}
result = collection.insert_one(new_profile)  # This is fine.
result = collection.insert_one(duplicate_profile)
Traceback (most recent call last):
DuplicateKeyError: E11000 duplicate key error index: test_database.profiles.$user_id_1 dup key: { : 212 }
Loading...
Loading...
Loading...
字段MongoDB 类型说明
StringFieldstring可加 regex、max_length 等约束
IntField / FloatFieldnumber可加 min_value / max_value
DecimalFieldnumbermin_value, max_value,precision=2
BooleanFieldbool
DateTimeFielddate常用 default=datetime.now
ListFieldarray必须嵌套一个字段类型
DictFieldobject任意结构的字典
EmbeddedDocumentFieldobject内嵌子文档
ReferenceFieldObjectId引用其他集合的文档
ObjectIdFieldObjectId手动管理主键
EmailField / URLFieldstring带格式校验
Loading...
Loading...