Search code examples
mongodbpython-2.7unidecoder

How to save non ASCII Characters in Mongo DB


This question is repeated, but I can not find answer to problem in my context. I am trying to save Aéropostale as string in mongo DB:

name='Aéropostale'
obj=Mongo_Object()
obj.name=name
obj.save()

When I save the object, I get following error:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128)

How to proceed to save the string in original format and retrieve in same format?


Solution

  • As you are using Python 2.7, you need to do a few things:

    1. Specify the file encoding, by adding a string similar to this to the top of your file:

      #coding: utf8
      
    2. Use a unicode string, as your string is not ASCII, and specify the encoding. I am using utf8 here which includes é:

      name = unicode('Aéropostale', 'utf8')