使用 find_one 获取文档 (pymongo)
Get a document with find_one (pymongo)
我得到了这样的文档结构:
{
"_id": "106.xxx.xxx.xxx",
"maxAge": 48,
"origin": "some_origin",
"time": "2016-07-04 11:41:47"
}
_id 包含一个 IP 地址,我想通过 pymongo 的 find_one 函数获得它。
我这样称呼它:
return (self.posts.find_one({"_id": ip}))
全部 returns 是 "none" 因为它没有找到文档。有什么想法吗?
编辑:
我也试着这样称呼它:
return (self.posts.find_one({"_id": str(ip)}))
更多信息:
我在 docker 容器中得到了一个名为 "vpn_service" 运行 的数据库。
该集合也被命名为 "vpn_service"。
首先我尝试像这样初始化 Mongoclient:
def __init__(self, host, port):
self.client = MongoClient(host=host, port=port)
self.db = self.client.vpn_service
self.posts = self.db.posts
我也试过这个:
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
因为 posts.find_one() 也没有找到任何东西,这可能是连接问题。
检查 ip
是否为字符串类型。这可能会在搜索过程中造成问题。如果不是,请尝试将其类型转换为字符串。
这意味着找不到文档。
确保文档存在并且您正在查询正确的类型 - 字符串。
同时测试你的 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
打印结果:
Collection(Database(MongoClient('localhost', 27017), u'test_db'), u'test_collection')
我得到了这样的文档结构:
{
"_id": "106.xxx.xxx.xxx",
"maxAge": 48,
"origin": "some_origin",
"time": "2016-07-04 11:41:47"
}
_id 包含一个 IP 地址,我想通过 pymongo 的 find_one 函数获得它。 我这样称呼它:
return (self.posts.find_one({"_id": ip}))
全部 returns 是 "none" 因为它没有找到文档。有什么想法吗?
编辑: 我也试着这样称呼它:
return (self.posts.find_one({"_id": str(ip)}))
更多信息: 我在 docker 容器中得到了一个名为 "vpn_service" 运行 的数据库。 该集合也被命名为 "vpn_service"。
首先我尝试像这样初始化 Mongoclient:
def __init__(self, host, port):
self.client = MongoClient(host=host, port=port)
self.db = self.client.vpn_service
self.posts = self.db.posts
我也试过这个:
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
因为 posts.find_one() 也没有找到任何东西,这可能是连接问题。
检查 ip
是否为字符串类型。这可能会在搜索过程中造成问题。如果不是,请尝试将其类型转换为字符串。
这意味着找不到文档。
确保文档存在并且您正在查询正确的类型 - 字符串。
同时测试你的 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
打印结果:
Collection(Database(MongoClient('localhost', 27017), u'test_db'), u'test_collection')