简体   繁体   中英

Pymongo - How can I return a specific field?

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))

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM