[英]Pymongo - How can I return a specific field?
I need the ObjectId of documents so I can put it in a list.我需要文档的 ObjectId 以便我可以将它放在列表中。 Visually I need
视觉上我需要
'_id':'ObjectId(x)'
Out of a bunch of documents.出一堆文件。 How can I return the Id of a document?
如何返回文档的 ID?
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:现在,假设您只有 Id = 123456789 并且您需要从数据库中找到附加到该 Id 的文档并返回大小:
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:要搜索集合中的所有文档并将 Id 存储在列表中:
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.您总是会得到
_id
字段,除非您特别要求不要得到它。
So it will be in the returned document(s) of your find()
or find_one()
statement.所以它将在您的
find()
或find_one()
语句的返回文档中。 For example:例如:
record = db.mycollection.find_one({})
print (record.get('_id'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.