python - 如何检查mongodb中列表字段的最后一项值
问题描述
嗨,我在 mongodb 数据库中有一个文档。我想检查列表中最后一个必填项的值。例如:
{
"id" : "123aaaa",
"position" : [
{
"centerId" : "AAAA",
"serviceId" : "BBBB"
},
{
"centerId" : "XXXX",
"serviceId" : "EEEE"
},
]
}
我想对“位置”进行降序排序并检查“centerId”的值。如果等于“AAAA”显示或不显示
解决方案
我认为您可以将您的位置列表转换为 Python 列表并使用 Python 的默认sorted
函数进行排序。
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["db_name"]
mycol = mydb["collection_name"]
myquery = { "id" : "123aaaa" } # This can be whatever query you want, or empty for ALL documents
mydocs = mycol.find(myquery) # Cursor to all documents
for doc in mydocs:
doc_position = doc["position"] # This is now a list of dicts
# You can just use Python's default "sorted" for sorting your list
sorted_doc_position = sorted(doc_position, # The list to sort
key=lambda x: x["centerId"], # The key to sort it by
reverse=True # Descending
)
if sorted_doc_position[0]["centerId"] == "AAAA": # Check if the first position is AAAA
show = True
推荐阅读
- statistics - 从所需的变量行为中查找条件(布尔值)
- css - 由于 CSS 问题,Wordpress 在移动设备上崩溃
- windows - 在控制台中生成二维码的简单方法是什么
- javascript - alpine.js 表就地编辑功能
- pip - ImportError: no module named "___" - Thonny, Ubuntu, Packages installed
- swift - 如何在静止图像上添加 ScrollView?
- python - 如何写入与打印格式相同的文件?
- android-studio - 安卓工作室 4.2
- authentication - 如何在数据库中正确存储 JWT 刷新令牌?
- firebase - Flutter-方法[]在null上被调用