如何使用正则表达式查询 pymongo 以获取仅包含数字的值

Posted

技术标签:

【中文标题】如何使用正则表达式查询 pymongo 以获取仅包含数字的值【英文标题】:how to query pymongo with regex for values containing only digits 【发布时间】:2021-08-18 22:39:28 【问题描述】:

我正在使用 mongodb 数据库,其中我在某些文档中具有特定值包含字段 parentDocId,而其他文档则不包含。除了 ParentDocId 有多种形状外,我还想获得 500 个文档,其中该字段不仅存在,而且包含 6 个或更多数字(没有其他字符)。这是我认为可行的查询:

import pymongo
query = "$and": ['docReferences.parentDocId':"$exists":True,
'docReferences.parentDocId':"$regex": "^[0-9][0-9][0-9][0-9][0-9]*$"]

但是这里应用的查询不起作用:

cur = DATA_collection.find(query).limit(500)
tic=datetime.now()
elements = []
for el in cur: 
    elements.append(el)
tac=datetime.now()
print(f'tac-tic')
print(len(elements))

这给了我一个相同文档的列表 500 次,并且不会过滤掉 parentDocId 像“1111”这样的文档

知道我做错了什么吗?

注意:使用时:

docReferences.parentDocId':"$isNumber":True

我明白了:

unknown operator: $isNumber,

【问题讨论】:

【参考方案1】:

六位或更多位(仅限)的正则表达式模式是^[0-9]6,$,因此您可以尝试:

import pymongo
query = 
    "$and": [
         'docReferences.parentDocId' :  "$exists" : True  ,
         'docReferences.parentDocId' :  "$regex": "^[0-9]6,$"  
    ]

【讨论】:

以上是关于如何使用正则表达式查询 pymongo 以获取仅包含数字的值的主要内容,如果未能解决你的问题,请参考以下文章

如何在 pymongo 中正确设计正则表达式?

PyMongo $in + $正则表达式

PyMongo 匹配 JavaScript 正则表达式对象

带有日期时间的 MongoDB / Pymongo 查询

Pymongo $regexMatch 正则表达式选项中的无效标志:u

100天精通Python(进阶篇)——第40天:pymongo操作MongoDB数据库基础+代码实战