mongodb 来自不同于 pymongo 的命令行的结果

mongodb result from commandline different then from pymongo

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

如果我这样做,从 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})

怎么了?

使用 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})

我刚刚发现您也可以使用 $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