-2

I need the ObjectId of documents so I can put it in a list. Visually I need

'_id':'ObjectId(x)'

Out of a bunch of documents. How can I return the Id of a document?

Updating the question for clarity.

Suppose you have a document:

doc1 = {"_id": ObjectId('123456789'),
        "name" : "John Doe",
        "shoe_size" : "7"
       }

And you need a specific attribute such as "name"

>>> name = doc1.get("name")
>>> print(name)
John Doe

Now, suppose you have only the Id = 123456789 and you need to find the document attached to that Id out of a database and return the size:

import pymongo
from pymongo import MongoClient
from bson import ObjectId

>>> URI = "URI" #link that gives you access to your database
>>> client = MongoClient(URI)
>>> db = client.get_database()
>>> print(db.collection.find_one({"_id":ObjectId("123456789")}).get("size))
7

To search all of the documents in a collection and store the Id's in a list:

lst_ids = []
collection = db.collection.find({})
for doc in collection:
   lst_ids.append(doc.get("_id))
anthonym650
  • 49
  • 1
  • 7
  • Does this answer your question? [How to select a single field for all documents in a MongoDB collection?](https://stackoverflow.com/questions/25589113/how-to-select-a-single-field-for-all-documents-in-a-mongodb-collection) – Joe Oct 03 '20 at 08:53

1 Answers1

1

You always get the _id field unless you specifically ask to not get it.

So it will be in the returned document(s) of your find() or find_one() statement. For example:

record = db.mycollection.find_one({})
print (record.get('_id'))
Belly Buster
  • 8,224
  • 2
  • 7
  • 20