-2

I have this mongodb document. I am using pymongo and I want to extract all the workout-names field as a dictionary and then use it to view them on a web page as a list.

{
"_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"
    }
    ]
}

I want to get all the workout names as a result like this:

{"Treadmill", "Pushups", "Squats"}

I tried making this query:

workouts.find_one({"username":session['username']}, {"workouts.workout-name" : , "_id" : 0})

and I got back this result:

{'workouts': [{'workout-name': 'Treadmill'}, {'workout-name': 'Squats'}, {'workout-name': 'Running'}]}

How can I improve my query to get the desired results?

  • Please refer this link https://stackoverflow.com/questions/13230284/convert-mongodb-return-object-to-dictionary – Surya Tej Jun 19 '18 at 09:52

1 Answers1

0

This code seems to work:

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'])