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.

This is equivalent to

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

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.