0
import pymongo

uri = "mongodb://127.0.0.1:27017"
client = pymongo.MongoClient(uri)
database = client['fullstack']
collection = database['students']

students = [student['mark'] for student in collection.find({}) if student['mark'] == 99.0]
print(students)

In the program above how does this work? Why is the if statement after the execution code? I would expect the if to be before the for. And if student['mark'] contains a value other than the string mark then it looks to me like student behaving like a dictionary with a key/value pair and not a python list. It probobly doesn't help that I've been playing in php and looks exactly like a php associative array.

2
Contributors
3
Replies
43
Views
1 Year
Discussion Span
Last Post by Gribouillis
1

This is equivalent to

tmp = []
for student in collection.find():
    if student['mark'] == 99.0:
        tmp.append(student['mark'])
students = tmp

Edited by Gribouillis

0

So is student a dictionary in each iteration of this code?

What student actually is depends on the pymongo api. You could print(type(student)) to see what it is. In the list comprehension, student can be any python instance for which the expression student['mark'] has a meaning.

Edited by Gribouillis

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.