如何使用 'LIKE' 语句过滤 mongoengine 中的对象?
How to filter objects in mongoengine using 'LIKE' statement?
我的 mongodb 中有以下 json 结构。
{
"country": "spain",
"language": "spanish",
"words": [
{
"word": "hello1",
....
},
{
"word": "hello2",
....
},
{
"word": "test",
....
},
]
}
我正在尝试获取 'words' 列表中具有特定子字符串匹配的所有词典。
例如,如果我有一个子字符串 'hel',那么我应该如何使用 mongoengine 查询我的文档,它给出了两个包含单词的字典:'hello1' 和 'hello2'
以下查询仅适用于不包含子字符串的匹配词。
data = Data.objects.filter(words__match={"word":"hel"})
// data is empty in this case([])
使用$elemMatch
(mongoengine 中的match
)将return 数组中符合条件的第一个元素。
您需要对数组中的return所有匹配元素使用聚合:
pipeline = [
{ "$unwind": "$words" },
{ "$match": {"words.word": {"$regex": "hel"} } },
{ "$project": {"word":"$words.word", "_id":0} },
]
Article.objects.aggregate(*pipeline)
结果:
{u'word': u'hello1'}
{u'word': u'hello2'}
请注意,使用此项目阶段您需要提前了解所有字段,以便您可以在投影中将它们指定为 return。
您也可以将此项目用于不同的输出,return 所有字段但包含在 'words dict':
中
pipeline = [
{ "$unwind": "$words" },
{ "$match": {"words.word": {"$regex": "hel"} } },
{ "$project": {"words":1, "_id":0} },
]
结果:
{u'words': {u'otherfield': 1.0, u'word': u'hello1'}}
{u'words': {u'otherfield': 1.0, u'word': u'hello2'}}
我的 mongodb 中有以下 json 结构。
{
"country": "spain",
"language": "spanish",
"words": [
{
"word": "hello1",
....
},
{
"word": "hello2",
....
},
{
"word": "test",
....
},
]
}
我正在尝试获取 'words' 列表中具有特定子字符串匹配的所有词典。
例如,如果我有一个子字符串 'hel',那么我应该如何使用 mongoengine 查询我的文档,它给出了两个包含单词的字典:'hello1' 和 'hello2'
以下查询仅适用于不包含子字符串的匹配词。
data = Data.objects.filter(words__match={"word":"hel"})
// data is empty in this case([])
使用$elemMatch
(mongoengine 中的match
)将return 数组中符合条件的第一个元素。
您需要对数组中的return所有匹配元素使用聚合:
pipeline = [
{ "$unwind": "$words" },
{ "$match": {"words.word": {"$regex": "hel"} } },
{ "$project": {"word":"$words.word", "_id":0} },
]
Article.objects.aggregate(*pipeline)
结果:
{u'word': u'hello1'}
{u'word': u'hello2'}
请注意,使用此项目阶段您需要提前了解所有字段,以便您可以在投影中将它们指定为 return。
您也可以将此项目用于不同的输出,return 所有字段但包含在 'words dict':
中pipeline = [
{ "$unwind": "$words" },
{ "$match": {"words.word": {"$regex": "hel"} } },
{ "$project": {"words":1, "_id":0} },
]
结果:
{u'words': {u'otherfield': 1.0, u'word': u'hello1'}}
{u'words': {u'otherfield': 1.0, u'word': u'hello2'}}