首页 > 解决方案 > 如何检查mongodb中列表字段的最后一项值

问题描述

嗨,我在 mongodb 数据库中有一个文档。我想检查列表中最后一个必填项的值。例如:

{
    "id" : "123aaaa",
    "position" : [
        {
            "centerId" : "AAAA",
            "serviceId" : "BBBB"
        },
        {
            "centerId" : "XXXX",
            "serviceId" : "EEEE"
        },

    ]
}

我想对“位置”进行降序排序并检查“centerId”的值。如果等于“AAAA”显示或不显示

标签: pythonmongodbpymongo

解决方案


我认为您可以将您的位置列表转换为 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

推荐阅读