2

I am trying to read data from mongodb database as below and running into couple of issues,can anyone provide guidance?

  1. Running into below error, how to fix this?

  2. Is there a way to do a case-insensitive search by regex, I have "\%train\%"as below, not sure if this is the right way

from pymongo import MongoClient
import os,pymongo
dbuser = os.environ.get('muser', 'techauto1')
dbpass = os.environ.get('mpwd', 'techpass')
uri = 'mongodb://{dbuser}:{dbpass}@machine.company.com:27017/techautomation'.format(**locals())
client = MongoClient(uri)
db = client.techautomation.tech_build_audit
try:
  #db.tech_build_audit
  myCursor = db.collection.find({"chip" : "4377","branch" : "\%train\%"}).sort({"_id":-1})
  print myCursor

except pymongo.errors.AutoReconnect, e:
  print e

Errors:

Traceback (most recent call last):

File "parseplist.py", line 11, in

myCursor = db.collection.find({"chip" : "4377","branch" : "%peaceB%"}).sort({"_id":-1})

File "/Library/Python/2.7/site-packages/pymongo/cursor.py", line 703, in sort keys = helpers._index_list(key_or_list, direction)

File "/Library/Python/2.7/site-packages/pymongo/helpers.py", line 52, in _index_list

raise TypeError("if no direction is specified, "

TypeError: if no direction is specified, key_or_list must be an instance of list

UPDATE:

I am not able to verify if the regex works because of the error,how do I fix the error?

Dmitrii Sidenko
  • 660
  • 6
  • 19
carte blanche
  • 10,796
  • 14
  • 46
  • 65

1 Answers1

1

you can use pythons re library for regex and re.IGNORECASE for your second problem, like this:

import re

### rest of your code
regx = re.compile("^foo", re.IGNORECASE)
myCursor = db.collection.find({"chip" : "4377","branch" : regx}).sort({"_id":-1})
print myCursor

About your updated question:

Thats another issue and its about using sort() with pymongo, you can see the answer here

In short you should use .sort() like this: .sort([("_id", -1)])

ganjim
  • 1,234
  • 1
  • 16
  • 30