How to return an optional field in the result

Hi,

Due to existing design, I have to check 2 fields with one optional to get last modified time of a record.
How can I return both fields in the result with one optional? Can I set a default value if it’s missing in the result?

Here is code snippet:

`new_changes = change_collection.find(
{“$or”: [{‘first_deployment_date’: {‘$exists’: True, ‘$gte’: src_last_change_date}},
{‘document_last_change_date’: {‘$exists’: True, ‘$gte’: src_last_change_date}}]},
{‘_id’: 1, ‘first_deployment_date’: 1, ‘document_last_change_date’: 1})

    if new_changes:  # it's just a cursor which could have no item, don't want to use count, prefer a next()
        doc_id_change_dates = []
        for change in new_changes:
            last_modified = change['document_last_change_date'] if change['document_last_change_date'] \
                            else change['first_deployment_date']
            doc_id_change_dates.append((change['_id'], last_modified))`

Thank you very much!

Mary

Hello,

Please see if it is helpful.

test> db.test.find({},{_id:0});
[ { a: 1 }, { a: 2, b: 2 } ]

db.test.find({},{a:1, b: {$ifNull:["$b",'b does not exist' ]}, _id:0});
[ { a: 1, b: 'b does not exist' }, { a: 2, b: 2 } ]

Thanks
WeDoTheBest4You

1 Like

Thanks. Yeah, I found out $ifNull and got it working by tests with local MongoDB. However, it’s not supported by DocumentDB yet and I have to change to another way using exclusion instead.

If more and more features missing in DocumentDB, we may consider change back to use MongoDB.