0

Data: I have 3 mongodb documents, two of them contain '04'.

It is working fine with mongo shell, but not when I script it with Python...

Let's see my documents and the regex find results as expected:

MongoDB shell version: 3.2.11
connecting to: 192.168.79.2/test
> db.virtuel.find({},{_id:0 , d:1})
    { "d" : "0409" }
    { "d" : "0204" }
    { "d" : "0710" }

> db.virtuel.find({ d: { $regex: '^\([0-9][0-9]\)*\(04\)\([0-9][0-9]\)*$' } }).count()
    2

But, when I want to code the same in Python:

import pymongo
myclient = pymongo.MongoClient("mongodb://192.168.79.2:27017/")
mydb = myclient["test"]
mycol = mydb["virtuel"]

regex_pd='^\([0-9][0-9]\)*\(04\)\([0-9][0-9]\)*$'

myquery={}
myquery['d'] = {
    u'$regex': regex_pd }
dataset = mycol.find(myquery)
print("Number of elements : " + str(dataset.count()))
mydb.close()

This returns 0 instead of 2 as expected... Sure, I made a mistake but which one?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
fdav
  • 1
  • 3
  • How about double escape: `regex_pd='^\\([0-9][0-9]\\)*\\(04\\)\\([0-9][0-9]\\)*$'` – Toto Dec 24 '18 at 11:01
  • Same result, when i print myquery, double escape are present – fdav Dec 24 '18 at 13:32
  • I think it's the other way around with escaping. I'm not good with Mongo shell, but if it's just JavaScript, then things like `\(` are actually interpreted as bare parenthesis. So you either need to double escape in MongoDB shell, and single escape in python or do no escaping at all. – kirilloid Dec 25 '18 at 12:24

0 Answers0