简体   繁体   English

使用find_one(pymongo)获取文档

[英]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. _id包含我想通过pymongo的find_one函数获得的IP地址。 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. 进一步的信息:我在docker容器中运行了一个名为“ vpn_service”的数据库。 The collection is alos named "vpn_service". 该集合还名为“ vpn_service”。

First i tried to init the Mongoclient like this: 首先,我试图像这样初始化Mongoclient:

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. 由于仅posts.find_one()找不到任何东西,因此连接可能有问题。

Check that if ip is of type string. 检查ip是否为字符串类型。 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): 还测试您的pymongo连接(用您的值更改我的值):

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') 集合(数据库(MongoClient('localhost',27017),u'test_db'),u'test_collection')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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