Search code examples
pythonmongoengineflask-mongoengine

python mongoenqine querying documents


I am querying 2 collections from mongodb. I am querying one collection that has a field called 'quiz_id'. I want to search for the value of this field (e.g. the first quiz_id value is 'M7001'). In the second collection, I want to search for value of the 'quiz_id' (it's a score from a quiz taken from 0 to 10) from the first query which is a key and return the value. Here is what I have:

quizzes = Topic_maths.objects.order_by('quiz_id')
quiz_chk = User.objects.filter(username=current_user)

for quiz_id in quizzes:
    print (quiz_id.quiz_id)
    key = quiz_id.quiz_id
    if key in quiz_chk:
        print ("score: ", key.quiz_id)
    else:
        print ("no score")

So the first part 'print (quiz_id.quiz_id)' prints each of the quiz id numbers ok. but I can't figure out how to search the mongo queryset returned for the key. For information:

print (quiz_id.quiz_id)
<class 'flask_mongoengine.BaseQuerySet'>

Any help would be greatly appreciated, thanks


Solution

  • quiz_chk requires additional iteration:

    [q['quiz_id'] for q in quiz_chk]

    which would make entire code look like that:

    from mongoengine import *
    
    connect('test')
    
    
    class TopicMaths(Document):
        quiz_id = StringField()
    
    
    class User(Document):
        username = StringField()
        quiz_id = StringField()
    
    
    current_user = 'Bob'
    
    quizzes = TopicMaths.objects.order_by('quiz_id')
    quiz_chk = User.objects.filter(username=current_user)
    
    for quiz_id in quizzes:
        print(quiz_id.quiz_id)
        key = quiz_id.quiz_id
        if key in [q['quiz_id'] for q in quiz_chk]:
            print("score: ", key)
        else:
            print("no score")
    

    Output:

    M7001
    no score
    M7002
    score:  M7002
    M7003
    no score