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'))
Sign up to request clarification or add additional context in comments.

Comments

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

You need to use ObjectId

5 Comments

I'm getting this NameError: name 'ObjectID' is not defined.
Its working for me here. Can you show all of your code here please.
Edited the question description with the imports Vivek.
I wanted to see if you are getting the object id correct. Can you show the code to get the object id?
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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.