简体   繁体   English

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

[英]how to query pymongo with regex for values containing only digits

I am working with a mongodb database where I have a particular value in some of the documents contain the field parentDocId, and others dont.我正在使用 mongodb 数据库,其中我在某些包含字段 parentDocId 的文档中具有特定值,而其他文档则没有。 Besides the ParentDocId is of many shapes, I would like to get 500 documents where that field not only exists but it is of 6 or more digits (no other character).除了 ParentDocId 有多种形状外,我还想获得 500 个文档,其中该字段不仅存在,而且包含 6 个或更多数字(没有其他字符)。 This is the query I thought it work:这是我认为可行的查询:

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

But the query applied here does not work:但是这里应用的查询不起作用:

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))

this gives me a list of the THE SAME DOCUMENT 500 times and does not filter out documents with parentDocId like '1111'这给了我 500 次相同文档的列表,并且不会过滤掉带有 parentDocId 的文档,例如“1111”

Some idea what I am doing wrong?一些想法我做错了什么?

NOTE: when using:注意:使用时:

docReferences.parentDocId':{"$isNumber":True}

I get:我得到:

unknown operator: $isNumber,

The regex pattern for six or more digits (only) is ^[0-9]{6,}$ , so you may try:六位或更多位(仅限)的正则表达式模式是^[0-9]{6,}$ ,因此您可以尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM