PhilipB
PhilipB

Reputation: 329

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.

Upvotes: 2

Views: 6164

Answers (2)

sergiuz
sergiuz

Reputation: 5539

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')

Upvotes: 0

ShivamGupta
ShivamGupta

Reputation: 41

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

Upvotes: 0

Related Questions