4

I'm using Python + MongoDB + PyMongo in Openshift

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)

When I query a file by _id, this is what I get.

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

When I query with the corresponding filename:

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

True

What could be possibly be going wrong?

Thanks.

2 Answers 2

16

For pymongo versions < 2.2, you need to import ObjectId with

from pymongo.objectid import ObjectId

For versions 2.2 and above, the import is instead

from bson.objectid import ObjectId

Then you can query gridfs like so:

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

You need to use ObjectId

5
  • I'm getting this NameError: name 'ObjectID' is not defined.
    – sbose
    Sep 9, 2012 at 13:52
  • Its working for me here. Can you show all of your code here please.
    – vivek
    Sep 9, 2012 at 14:15
  • Edited the question description with the imports Vivek.
    – sbose
    Sep 9, 2012 at 14:23
  • I wanted to see if you are getting the object id correct. Can you show the code to get the object id?
    – vivek
    Sep 9, 2012 at 14:45
  • No no. Let mongo generate ObjectIds. When you put/write object into the mongo db through gridfs, you'll get an object id. Use that.
    – vivek
    Sep 10, 2012 at 5:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.