我有这个mongodb文件。我正在使用pymongo,我想将所有 exercise-names 字段提取为字典,然后使用它在网页上以列表的形式查看它们。
{
"_id" : ObjectId("5b28bfed9ebcea299d08976e"),
"username" : "cybr1998@gmail.com",
"workouts" : [
{
"workout-name" : "Treadmill",
"workout-duration" : "1",
"workout-frequency" : "Everyday",
"_id" : "td"
},
{
"workout-name" : "Squats",
"workout-duration" : "1",
"workout-frequency" : "Everyday",
"_id" : "sq"
},
{
"workout-name" : "Running",
"workout-duration" : "0.5",
"workout-frequency" : "Everyday",
"_id" : "rn"
}
]
}
我希望得到所有锻炼名称,如下所示:
{"Treadmill", "Pushups", "Squats"}
我尝试过这个查询:
workouts.find_one({"username":session['username']}, {"workouts.workout-name" : , "_id" : 0})
我收回了这个结果:
{'workouts': [{'workout-name': 'Treadmill'}, {'workout-name': 'Squats'}, {'workout-name': 'Running'}]}
如何改进查询以获得所需的结果?
答案 0 :(得分:0)
此代码似乎有效:
list_workouts = []
available_workouts = workouts.find_one({"username": session['username']}, {"workouts.workout-name": 1, "_id": 0})
list_len = len(available_workouts['workouts'])
for i in range(0, list_len):
list_workouts.append(available_workouts['workouts'][i]['workout-name'])