mongodb的命令行结果不同于pymong

2024-05-14 22:03:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试根据查找的结果创建一个新集合。你知道吗

从mongodb(机器人)命令行如果我这样做

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)

也像这样使用regex没有结果。。。你知道吗

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

怎么了?你知道吗


Tags: theimportredbmongodblicurrentfind
2条回答

我发现你也可以使用$regex语法。 您不需要导入re模块和使用python regex:只需添加$options参数,它也可以在pymongo上工作。你知道吗

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

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

对于pymongo,在regex中不使用斜杠作为分隔符,因为您使用的是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})

相关问题 更多 >

    热门问题