0

I'm querying mongo for a set of objects using mongoengine and I have to return the results as an array of JSON.

This is how the object is defined:

class OptimisedSummary(Document):
    date_from = DateTimeField()
    date_to = DateTimeField()
    (...)

This is how I'm returning the data:

return OptimisedSummary.objects(date_from__gte=_date_from, date_to__lte=_date_to).to_json()

The problem is that my objects have date fields, and they are comming like this:

"date_from": {
            "$date": 1534334450799
        },
"date_to": {
            "$date": 1534420850799
        },

There is any way to pre-format those to return them in a readable format?

I appreciate any help, thanks

magnoz
  • 1,939
  • 5
  • 22
  • 42

1 Answers1

0

I've found a way to actually make this work, I wonder, though, if there is a better approach to this.

This is what I did:

pipeline = [
    {
        "$match": {
            "date_from": {"$gte": _date_from},
            "date_to": {"$lte": _date_to}
        }
    },
    {
        "$project": {"array": True,
                     "date_from": {
                         "$dateToString": {
                             "format": "%Y-%m-%d",
                             "date": "$date_from"
                         }
                     },
                     "date_to": {
                         "$dateToString": {
                             "format": "%Y-%m-%d",
                             "date": "$date_to"
                         }
                     },
                     "field1": 1,
                     "field2": 1
                     }
    }
]

result = OptimisedSummary.objects.aggregate(*pipeline)

return JSONEncoder().encode(list(result))

It works.

magnoz
  • 1,939
  • 5
  • 22
  • 42