Header logo.
Tonghe's Notes

Week 46 gave me surprises

A few things:

Handling date and time is more complicated than I expected. python-dateutil is quite helpful when you need to parse a datetime string.

A pitfall

I tried updating a field in a MongoDB document using MongoEngine. The value of that field was an embedded document that contained four sub-fields. I intended to change the value of subkey2. But the entire embedded document was overwritten.

    key1: value1,
    key2: value2,
    key3: {
        subkey1: subvalue1,
        subkey2: subvalue2,
        subkey3, subvalue3

    # After updating, this field instead became this...
    # ...and this is not what I wanted
    key3: {
        subkey2: newvalue

I'm quite glad I caught this potential bug early on. And indeed, smart people out there have figured it out.

Baffling decimals

I was trying to check if the submitted value and the value found in MongoDB are the same. This field was defined as a decimal.

In order to try it out, I artificially submitted a JSON object that contained a number with two decimal places (69.30) and the value I saved in MongoDB was 69.3 of decimal type (or I thought so).

But Decimal(submitted_value) == Decimal(mongodb_value) returned False.

Printing out the two values, I got:

# submitted_value
# mongodb_value

The reason of this turned out to be: Although I defined this field to be a DecimalField with precision=2 in MongoEngine, the value actually stored in MongoDB was still a Double.

And a float number is supposed to do this.