'Convert a Python type to a MongoDB compatible type.'

def to_mongo(self, value, use_db_field=True, fields=None):

    if isinstance(value, six.string_types):
        return value
    if hasattr(value, 'to_mongo'):
        cls = value.__class__
        val = value.to_mongo(use_db_field, fields)
        if isinstance(value, Document):
            val = {'_ref': value.to_dbref(), '_cls': cls.__name__}
        if isinstance(value, EmbeddedDocument):
            val['_cls'] = cls.__name__
        return val
    if (not isinstance(value, (dict, list, tuple))):
        return value
    is_list = False
    if (not hasattr(value, 'items')):
        is_list = True
        value = {k: v for (k, v) in enumerate(value)}
    data = {}
    for (k, v) in value.iteritems():
        data[k] = self.to_mongo(v, use_db_field, fields)
    value = data
    if is_list:
        value = [v for (k, v) in sorted(data.iteritems(), key=itemgetter(0))]
    return value
