由于源是数组,如何使用Icontains在ListField中进行搜索?

时间:2018-09-29 17:37:13

标签: python django mongodb

我正在使用Django查询MongoDB中的数据。我的数据库中有此文档:

{
"source": "www.google.com",
"hierarchies": [],
"mainTags": [
    "Sobre a página",
    "Teste Tag",
    "Cartão de Crédito"
],
"email": "a@a.com",
"_id": {
    "$oid": "5ba7ffee2ef3f4139de74f3d"
},
"updated_at": {
    "$date": 1537725886501
},
"created_at": {
    "$date": 1537725886501
},
"title": "Relação de seguros entre 2017 e 2016",
"tableId": "relacao_de_seguros_entre_2017_e_2016_7836c6e2",
"relevance": 1.0,
"description": "este dataset tem como função mostrar a Relação de seguros entre 2017 e 2016",
"tags": []

}

我的输入应类似于:["Sobre", "Teste"]

我正在尝试查找所有 Maintag 包含任何 entry 值的文档。这就是我所做的:

    for word in keywordsArray:
        q |= Q(mainTags__icontains = word)
    objects = Metadata.objects.all().filter(q).order_by('relevance')

我也尝试过:

    objects = Metadata.objects.all().filter(Q(mainTags__in=mongoKeywords)).order_by('relevance')

但是当我通过["Sobre", "Teste"]作为条目时,它什么也没找到。怎么实现呢?

谢谢!

1 个答案:

答案 0 :(得分:0)

好吧,我不知道django,但这在普通的mongoshell查询中有效。它将找到标签为Sobre或Teste的所有文档。 / i表示忽略案例搜索

db.collectionName.find({
"mainTags": {"$regex":/^Sobre$|^Teste$/i}
})

其他选项是:

db.collectionName.find({
    "mainTags": {"$in":["Sobre","Teste"]}
})