MongoDB - 检查是否存在于dicts列表的列表中

时间:2014-11-30 12:58:11

标签: python mongodb python-2.7 pymongo

我正在尝试查找所有记录,其中值位于词典列表中字典的列表中。这是清单:

    "Tasks": [
    {
        "description": "Buy weekly groceries",
        "title": "Shopping",
        "notes": "See if any offers for milk",
        "completed": [
            "completed"
        ],
        "resources": [
            "246",
            "444"
        ]
    },
     {
        "description": "Fix car",
        "title": "Mechanics",
        "notes": "Change oil",
        "completed": [
            "completed"
        ],
        "resources": [
            "2589",
            "4818"
        ]
    }

]

我正在尝试返回任务列表中的所有dicts,其中246是资源'列表'中的值,如下所示:

db.projects.find({ "Tasks.resources":{ '$in': ["246"] }})

返回<pymongo.cursor.Cursor object at 0x030A10F0>,而不是任务,其中246在资源列表中。

1 个答案:

答案 0 :(得分:1)

find会返回一个游标。如果您想要对象,请尝试使用findOne()。请参阅web mongodb中的以下内容。您的代码按预期工作。

> var a = {"Tasks": [
    {
        "description": "Buy weekly groceries",
        "title": "Shopping",
        "notes": "See if any offers for milk",
        "completed": [
            "completed"
        ],
        "resources": [
            "246",
            "444"
        ]
    },
     {
        "description": "Fix car",
        "title": "Mechanics",
        "notes": "Change oil",
        "completed": [
            "completed"
        ],
        "resources": [
            "2589",
            "4818"
        ]
    }

]}


> db.projects.insert(a);
WriteResult({ "nInserted" : 1 })
> 
> db.projects.find({ "Tasks.resources":{ '$in': ["246"] }})
{
    "_id" : ObjectId("547b15e440694714925be65c"),
    "Tasks" : [
        {
            "notes" : "See if any offers for milk",
            "title" : "Shopping",
            "completed" : [
                "completed"
            ],
            "resources" : [
                "246",
                "444"
            ],
            "description" : "Buy weekly groceries"
        },
        {
            "notes" : "Change oil",
            "title" : "Mechanics",
            "completed" : [
                "completed"
            ],
            "resources" : [
                "2589",
                "4818"
            ],
            "description" : "Fix car"
        }
    ]
}

例如,将其更改为列表。

def l = list(projects.find({ "Tasks.resources":{ '$in': ["246"] }}))
print l 

for task in projects.find({ "Tasks.resources":{ '$in': ["246"] }}):
   print task

请参阅pymongo tutorial