简体   繁体   中英

PyMongo find_one does not return an existing entry

I'm having a strange issue with Pymongo's find_one function. I have a db called "cluster_db" hosted on my local machine. It has a collection called 'clusters'. When I run the query in the mongo shell I get following output.

> db
cluster_db
> db.clusters.findOne({_id:-8488068664808428000})
{
    "_id" : NumberLong("-8488068664808427924"),
    "members" : [
        {
            "participationCoeff" : 1,
            "tweetID" : NumberLong("-8488068664808427924")
        }
    ]
}
> 

Now, during my code initialization phase I have a constant defined in a module 'dbutil' like this:

DB_CONNECTION           = MongoClient('localhost', 27017)
CLUSTER_DB_HANDLE       = DB_CONNECTION['cluster_db']

After this, within a function, I'm making following call.

dbutil.CLUSTER_DB_HANDLE.clusters.find_one({'_id':clusterID})

However, the above call always returns 'None'. If I go to MongoShell and run the exact same query with same clusterID, I see the result.

I know that it is a strange error, but somehow I'm not able to figure out as to why this is happening. Everywhere else, I'm being able to successfully make calls to 'clusters' collection in cluster_db using dbutil.CLUSTER_DB_HANDLE.clusters

Just came across this myself and it turns out that the id I passed in is int type and I had to convert it by calling int(id), eg:

db.Employees.find_one({'id' : int(id)}) // this works
db.Employees.find_one({'id' : id}) //this doesn't work

Hope this helps someone.

is clusterID == -8488068664808428000 ? why don't you try CLUSTER_DB_HANDLE.clusters.find_one({'_id':-8488068664808428000}) ?

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