简体   繁体   中英

mongodb result from commandline different then from pymongo

I am trying to create a new collection based on a result from a find.

From the mongodb(robomongo) commandline if I do this

db.liCollection.find({current_companies : { $regex: /^DIKW/i }})

I get nice restult of 11 documents out of 2.6 million.

Now if I try to use pymongo like this:

from pymongo import MongoClient

uri = "mongodb://user:password@example.com/the_database"
client = MongoClient('pcloud')

# connect to the liDB
li_db = client['liDB']

#get all dikw employees
dikw_current = li_db.liCollection.find({'current_companies':{'$regex':'/^DIKW/i'}})

list(dikw_current)

Also like this using regex no result...

import re
regx = re.compile("/^DIKW/i", re.IGNORECASE)
li_db.liCollection.find_one({"current_companies": regx})

whats wrong?

With pymongo you don't use slash as delimiter in your regex since your are using python regular expressions. See why

Change your query to li_db.liCollection.find_one({"current_companies": "^DIKW"}) .If you need to specify options in your regex use re.compile

import re
regx = re.compile("^DIKW", re.IGNORECASE)
li_db.liCollection.find_one({"current_companies": regx})

I've just found you could also use the $regex syntax. You don't need to import re module and to use python regex: simply add the $options param, it will work on pymongo as well.

db.liCollection.find({'current_companies' : {'$regex': '^DIKW', '$options': 'i'}})

Source: https://docs.mongodb.org/manual/reference/operator/query/regex/#op._S_options

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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