使用正则表达式在多个值中查找字符串的有效方法

时间:2018-06-10 08:59:54

标签: python mongodb pymongo

如果一个字符串确实存在于对象的多个字段中,是否有办法找到对象?我尝试了or,但不是返回包含apple的对象,而是只返回一个项目。

mongodb的

[{"title": "Apple is good"}, {"description": "Orange is not an aPplE."}]

脚本

from mongo import db


query = 'apple'
res = db.article.aggregate([
    {
        "$match": {
            "$or": [
                {
                    "title": {
                        "$regex": query, "$options": "i"
                    },
                    "description": {
                        "$regex": query, "$options": "i"
                    }
                }
            ]
        }
    },
    {
        "$sample": {
            "size": 15
        }
    }
])

print(list(res))
# list(res) should be
# [{"title": "Apple is good"}, {"description": "Orange is not an apple."}]

0 个答案:

没有答案