You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Firestore中按document_id排序查询集合?

Python中Firestore按Document ID排序的实现方法

在Python的Firestore SDK里,你可以用firestore.FieldPath.document_id()来实现按文档ID排序,和JavaScript里的FieldPath.documentId()逻辑完全一致,直接把它传入orderBy()方法即可。

基础升序排序示例

import firebase_admin
from firebase_admin import firestore

# 初始化Firebase应用(未初始化时执行)
firebase_admin.initialize_app()

db = firestore.client()

# 按文档ID升序查询集合
query = db.collection("你的集合名称").order_by(firestore.FieldPath.document_id())
docs = query.get()

# 遍历输出结果
for doc in docs:
    print(f"文档ID: {doc.id}, 内容: {doc.to_dict()}")

降序排序示例

如果需要按文档ID降序排列,只需添加direction参数:

query = db.collection("你的集合名称").order_by(
    firestore.FieldPath.document_id(),
    direction=firestore.Query.DESCENDING
)
docs = query.get()

这个firestore.FieldPath.document_id()就是Python SDK中专门用于指代文档ID的字段路径,作用和你熟悉的JavaScript版本完全一致,只是写法略有不同。

内容的提问来源于stack exchange,提问作者Vikramark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 03:15:39