pythonmongodbflaskmongoengineflask-mongoengine

How can I find if any user with given ID exists on an array of arrays using flask and mongoengine?


I have a collection with multiple Course documents. On it, i have an array of course_users like the following example:

User in course example

Like this, I can have multiple courses in the same collection.

My purpose is to do something with any given User id, but first, I need to know if this user exists on any of the courses of the collection, for example, if User with an ID of 123 is on Course A OR Course B, I should return True. If user with an ID 456 is not on any Course I should return False.

Is there a way to make this query in as few steps as possible using mongoengine in flask?

My idea was to use the $ operator like the following:

def userIsInCourse(user_id):
    course_students = Course.objects(students__S__in=[user_id])
    print(course_students)

Thinking that Course.objects will retrieve every course filtered with students__S__in=user_id_ but I'm failing.

Sorry for the vague question.


Solution

  • I ended up modifying my query. Instead of trying to use the $ operator, I modified my query to use a raw query:

    def userIsInCourse(user_id):
        course_students = Course.objects(__raw__={'students': {'$elemMatch': {'student_id': user_id}}})
        if course_students:
            return True
        else:
            return False
    

    It retrieves the whole Courses array, and looks in each Course's students array of objects, then filters using the given user's id. If the user exists on the course, returns true.

    With this approach it was simpler than i thought.