jeudi 19 mars 2020

If condition for part of PyMongo Query

Can I add a python if statement for part of the pymongo query?

I want to add the lookup and unwind in the query only if it meets the condition.

If statement:

if user > 0:
  get_user = {'$lookup':
         {
             'from': 'user_logs',
             'localField': 'company',
             'foreignField': 'data.id',
             'as': 'users'
   }}
 user_unwind = {'$unwind': '$users'}

Query:

query = company.aggregate([
             get_user_logs, get_user_unwind, 
            {
                '$project': {
                    '_id': 0,
                     .
                     .
                     .
                    }
            }
        ])

When the condition is met, the query works fine. When the condition is not met I get the UnboundLocalError: local variable 'get_user' referenced before assignment error.

What is wrong with what I am doing?

Aucun commentaire:

Enregistrer un commentaire