0

I am trying to print all the object ids in a collection I have in mongoDB. I understand how to convert the ObjectId to a string, however I am not sure how to actually make a call to list all the object ids.

I tried the following from pymongo documentation but nothing happens because I have 4 ObjectIds

def get(post_id):
    Document=client.db.collection.find_one({'_id':ObjectId(post_id)})
    return Document
3
  • Hi joseph; can you explain what you mean when you say you have four ObjectIds, and how this makes the database query go wrong? Commented Mar 31, 2017 at 16:23
  • In my mongodb, I have a collection. Under that collection, there are four different objectIDs. I want to be able to return all 4 different object ids because afterwards i have a function that updates the database data but the data that needs to be updated depends on the object id. For example data X must be updated to object id X, data y to object id y, etc Commented Mar 31, 2017 at 17:52
  • Running the above code returns nothing. I want it to return the 4 unique object ids Commented Mar 31, 2017 at 17:53

1 Answer 1

3
from bson import ObjectId

id = "5fec2c0b348df9f22156cc07"
objInstance = ObjectId(id)
  
collection.find_one({"_id": objInstance})
  
# below line works same as the above
collection.find_one({"_id": ObjectId(id)})
collection.find_one(ObjectId(id))

bson should already been installed once you installed pymongo

Sign up to request clarification or add additional context in comments.

Comments

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.