Q:

How to return a array of null elements if array doesn't exist in mongodb using pymongo

Hi Guys I've a Json like this 
 {
  "_id":"15b9367568b61a0a2891feef",
  "date":1492826657037,
  "sourceId":123",
  "sessionCreationDate":1492826657037,
  "sessionId":"15b9367568dcd6dcd36f7615",
  "actions":[
     {
      "flag":"STARTED_SCROLL"
     },
     {
      "flag":"ARTICLE_MIDDLE"
     }
  ],
  "dateClose":1492826915066
}

how ever for some id's the 'actions' array might not exist aswell so something like this is possible
{
 "_id":"15b9367568b61a0a2891feef",
 "date":1492826657037,
 "sourceId":123,
 "sessionCreationDate":1492826657037,
 "sessionId":"15b9367568dcd6dcd36f7615"
}

my current query using pymongo is 
db['visits'].aggregate\
        (
                        [
                            {
                            "$match":
                                {
                                  "sourceId":
                                    {
                                        "$exists": True,
                                        "$ne": None
                                    },
                                  "date":
                                    {
                                        "$gt":time.time() * 1000 - (1*60*60*1000)
                                    }
                                }
                            },
                        {
                            '$project':
                                {
                                    'sourceId':1,
                            'actions.flag':
                                {
                                    '$ifNull': ['$actions.flag', None]
                                }

                            }
                        }
                    ]
        )

which results actions as dictionary actions': {u'flag': None} how do I convert this to a list of dictionary like [actions': {u'flag': [None]}]? because I want to access the flag variable to insert into my db but calling ['actions'][0]['flag'] in a for loop doesn't work as actions is not a list for those action items returned from mongo query and it breaks

A:

Put this in your $project stage instead:
{
    '$project':
        {
            'sourceId': 1,
            'actions.flag':
                {
                    '$ifNull': ['$actions.flag',
                                [None, None]]
                }
        }
}

