2012-09-09 42 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