简体   繁体   中英

Get a document with find_one (pymongo)

I got a documentstructure like this:

{
    "_id": "106.xxx.xxx.xxx",
    "maxAge": 48,
    "origin": "some_origin",
    "time": "2016-07-04 11:41:47"
}

_id contains an IP-Adress which i want to get with the find_one function of pymongo. I am calling it like this:

return (self.posts.find_one({"_id": ip}))

All it returns is "none" since it is not finding the document. Any Ideas?

Edit: I also tried to call it like:

return (self.posts.find_one({"_id": str(ip)}))

Further Information: I got a database called "vpn_service" running in a docker container. The collection is alos named "vpn_service".

First i tried to init the Mongoclient like this:

def __init__(self, host, port):
    self.client = MongoClient(host=host, port=port)
    self.db = self.client.vpn_service
    self.posts = self.db.posts

I also tried this:

def __init__(self, host, port):
    self.client = MongoClient(host=host, port=port)
    self.db = self.client.vpn_service
    self.collection = self.db.vpn_service
    self.posts = self.collection.posts

Since just posts.find_one() doesn't find anything either it's probably a problem with the connection.

Check that if ip is of type string. This might be creating the problem during search. If its not try typecasting it to string.

That means it cannot find the document.

Be sure that the document exist and you are querying on the correct type - string.

Also test your pymongo connection (change my values with yours):

from pymongo import MongoClient
client = MongoClient('localhost')
db_name = 'test_db'
db = client[db_name]
collection_name = 'test_collection'
collection = db[collection_name]
print collection

print result:

Collection(Database(MongoClient('localhost', 27017), u'test_db'), u'test_collection')

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