首页 > 解决方案 > Mongoengine:匹配重音字符作为基础字符

问题描述

相关:如何在 MongoDB db.foo.find() 语法中执行此操作

假设我有一个模型

class Foo(Document):
    name = StringField()

该集合的数据库状态为:

[{"name":"Jesús"},{"name":"Jesus"}]

我想要一个匹配两个文档的查询,即搜索,但变音符号标准化,例如:

Foo.objects.filter(name__icontains="jesus")

有没有办法直接在mongoengine中做到这一点?

标签: pythonstringmongodbmongoengine

解决方案


使用python,您可以import unidecode,然后将所有重音符号与普通文本进行比较,

from unidecode import unidecode
li = [ ]
for entry in Foo.objects:
    if unidecode(entry.name) == "Jesus":
        li.append(entry)

# now li has your filtered entries

或者,你可以做

from unidecode import unidecode
li = [ entry for entry in Foo.objects if unidecode(entry.name) == "Jesus" ]

注意:您必须unidecode使用pip install unidecode.

编辑:以下代码按预期工作,

>>> unidecode('Jesús')
Jesus

推荐阅读