【问题标题】:mongodb result from commandline different then from pymongo命令行的mongodb结果与pymongo不同
【发布时间】:2015-05-07 07:03:32
【问题描述】:

我正在尝试根据查找结果创建一个新集合。

如果我这样做,从 mongodb(robomongo) 命令行

db.liCollection.find({current_companies : { $regex: /^DIKW/i }})

我从 260 万份文件中的 11 份文件中得到了不错的结果。

现在,如果我尝试像这样使用 pymongo:

from pymongo import MongoClient

uri = "mongodb://user:password@example.com/the_database"
client = MongoClient('pcloud')

# connect to the liDB
li_db = client['liDB']

#get all dikw employees
dikw_current = li_db.liCollection.find({'current_companies':{'$regex':'/^DIKW/i'}})

list(dikw_current)

也像这样使用正则表达式没有结果...

import re
regx = re.compile("/^DIKW/i", re.IGNORECASE)
li_db.liCollection.find_one({"current_companies": regx})

怎么了?

【问题讨论】:

    标签: python regex mongodb pymongo


    【解决方案1】:

    使用 pymongo,您不会在正则表达式中使用斜杠作为分隔符,因为您使用的是 python 正则表达式。见why

    将您的查询更改为li_db.liCollection.find_one({"current_companies": "^DIKW"})。如果您需要在正则表达式中指定选项,请使用re.compile

    import re
    regx = re.compile("^DIKW", re.IGNORECASE)
    li_db.liCollection.find_one({"current_companies": regx})
    

    【讨论】:

      【解决方案2】:

      我刚刚发现您也可以使用$regex 语法。 您不需要导入 re 模块并使用 python 正则表达式:只需添加 $options 参数,它也可以在 pymongo 上运行。

      db.liCollection.find({'current_companies' : {'$regex': '^DIKW', '$options': 'i'}})
      

      来源:https://docs.mongodb.org/manual/reference/operator/query/regex/#op._S_options

      【讨论】:

        猜你喜欢
        • 2015-10-25
        • 1970-01-01
        • 1970-01-01
        • 2014-08-08
        • 1970-01-01
        • 2018-04-23
        • 2019-05-04
        • 2019-11-26
        • 1970-01-01
        相关资源
        最近更新 更多