2012-09-09 41 views
3

我使用Python +的MongoDB + PyMongo查询通过“_id”不MongoDB中在Python中Openshift返回文件,使用PyMongo

import os 
import gridfs 
from django.http import HttpResponse 
from pymongo.connection import Connection 
from django.shortcuts import get_object_or_404, render_to_response 
from django.http import HttpResponseRedirect, HttpResponse 
from django.template import Context, RequestContext,loader 

connection = Connection('mongodb://sbose78:[email protected]:10068/BOSE') 
db=connection['BOSE'] 
fs=gridfs.GridFS(db) 

当我通过查询_id一个文件,这就是我得到。

>>> fs.exists({"_id":'504a36d93324f20944247af2'}) 
False 

当我与相应的文件名查询:

>>> fs.exists({"filename":'foo.txt'}) 

True 

什么能可能会错误?

谢谢。

回答

10

对于pymongo版本< 2.2,你需要导入的ObjectId与

from pymongo.objectid import ObjectId 

对于2.2及以上版本,进口反而

from bson.objectid import ObjectId 

然后你可以像这样查询gridfs:

fs.exists(ObjectId('504a36d93324f20944247af2')) 
0
fs.exists({"_id":ObjectId('504a36d93324f20944247af2')}) 

您需要使用ObjectId

+0

我得到这个 NameError:name'ObjectID'未定义。 – sbose

+0

同样的问题Vivek。 – sbose

+0

它在这里工作。你能在这里展示你的所有代码吗? – vivek