使用PyMongo问题执行正则表达式查询



我正在尝试使用PyMongo对MongoDB服务器执行regex查询。文件结构如下。

{
"_id" : ObjectId("6076d2598128b279dfd62b1d"),
"transactionId" : "Test_Operation_112",
"requestA" : {
"pState" : "{"key1":"value1","key2":"value2"}",
"request" : "{"header":{"sender":{"login":"XXXXXXXXXX","password":"XXXXXXXXXX"},"notification":{"url":"https://example.com/pqr"},"transactionId":"Test_Operation_112","timeStamp":"04/13/2021 12:30:25-07:00"},"order":{"action":"CANCEL"}]}}}"
},
"requestTimeStamp" : "04/13/2021 12:30:25-07:00",
"responsesA" : {
"response" : "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><Response System='HGGH' xsi:noNamespaceSchemaLocation='Response.xsd' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Header TransactionId='Test_Operation_112'  TimeStamp='04/13/2021 12:30:25-07:00'><Sender Login='XXXXXXXXXX' Password='XXXXXXXXXX'/><Notification URL='https://example.com/pqr'/><TransactionCode MajorCode='0' Description='Success'><TransactionCodeList ErrorCode='0' ErrorMessageText='Service Removed'/></Response>"
},
"lastUpdatedTime" : ISODate("2021-04-14T11:30:33.605Z")
}
{
"_id" : ObjectId("6076d2598128b279dfd62b1d"),
"transactionId" : "XYZ123123_7_Test$a1b2c3",
"requestA" : {
"pState" : "{"key1":"value1","key2":"value2"}",
"request" : "{"header":{"sender":{"login":"XXXXXXXXXX","password":"XXXXXXXXXX"},"notification":{"url":"https://example.com/pqr"},"transactionId":"XYZ123123_7_Test$a1b2c3","timeStamp":"04/13/2021 12:30:25-07:00"},"order":{"action":"CANCEL"}]}}}"
},
"requestTimeStamp" : "04/13/2021 12:30:30-07:00",
"responsesA" : {
"response" : "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><Response System='HGGH' xsi:noNamespaceSchemaLocation='Response.xsd' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Header TransactionId='XYZ123123_7_Test$a1b2c3'  TimeStamp='04/13/2021 12:30:25-07:00'><Sender Login='XXXXXXXXXX' Password='XXXXXXXXXX'/><Notification URL='https://example.com/pqr'/><TransactionCode MajorCode='0' Description='Success'><TransactionCodeList ErrorCode='0' ErrorMessageText='Service Removed'/></Response>"
},
"lastUpdatedTime" : ISODate("2021-04-14T11:30:33.605Z")
}

有不同类型的事务ID。我想获得与事务ID的模式匹配的所有记录。Regex模式是正确的。我试着这样做

db.collectionName.find({"$and": [
{"requestTimeStamp": {"$gte": '04/13/2021 00:00:00-00:00', "$lte": '04/13/2021 23:59:59-00:00'}},
{"responsesA.response": {"$regex":  "ErrorCode='0'"}},
{"requestA.request": {"$regex": "CANCEL"}}, 
{ "transactionId": { "$in": [/^Test_Operation_d*/, /^XYZd*_d_Test$S*/] } }]});

然而我一无所获。我是不是错过了什么,因为根据MongoDB文档,这应该是可能的?如果我在Mongo控制台中执行查询,它可以正常工作,这是否意味着API不支持它,或者我只是使用不正确?

几件事。CCD_ 1返回一个光标;你必须对它进行迭代才能得到结果。您不需要$and部分,因为查询默认为and。您的正则表达式可以简化(请参阅代码(。

把它放在一起:

cursor = db.collectionName.find(
{"requestTimeStamp": {"$gte": '04/13/2021 00:00:00-00:00', "$lte": '04/13/2021 23:59:59-00:00'},
"responsesA.response": {"$regex": "ErrorCode='0'"},
"requestA.request": {"$regex": "CANCEL"},
"transactionId": {'$regex': '^Test_Operation_d*|^XYZd*_d_Test$S*'}})
print(list(cursor))

最新更新