我正在尝试查找所有记录,其中值位于词典列表中字典的列表中。这是清单:
"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在资源列表中。
答案 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。