mongodb - 搜索文档 : pymongo 的 ObjectId

标签 mongodb pymongo

我想通过“名称”属性访问集合中的文档以获取其 ObjectId,以便我可以将该唯一的 objectid 插入其他文档以供引用。

cursorObject = db.collectionIngredient.find({'name': 'sugar'})

我想要 cursorObject 的 _id 字段。

cursorObject.'_id' or cursorObject._id not working.

我尝试了__getitem____getattribute__ 等了很多次上网,但都找不到方法。

请帮忙

最佳答案

首先,正如@jjmartinez 指出的那样,find 返回一个游标,您需要对其进行迭代,以便获取查询返回的文档_id 字段属于文档,而不是光标。

我猜你的名字是唯一的,所以如果你使用 find_one 而不是 find 就可以避免游标/迭代。然后直接拿到文档。

然后,要访问 _id,您只需要一个标准的 dict-item 访问:

id = doc['_id']

所以我们得到:

ingredient = db.collectionIngredient.find_one({'name': 'sugar'})
if ingredient is not None:
    id = ingredient['_id']
else:
    id = None

关于mongodb - 搜索文档 : pymongo 的 ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20717439/

相关文章:

python - 为什么 MongoDB 在 Celery 连接上无法识别我的用户?

mongodb - Sitecore 8.1 错误 : "No session Id managers were found to manage the session Id for the current request"

arrays - 在不知道索引的情况下在数组中查找字典 mongodb

python - pymongo db.collection.update操作失败

python-3.x - 如何使用查找过滤器在 PythonEve 中使用 PyMongo 对结果进行排序

Django + mongoengine,作为辅助数据库时连接mongo

mongodb - Mongoose 过期属性无法正常工作

linux - 如何从 EC2 上的根卷创建 XFS 卷?

python - 为什么使用 update_one 更新记录会引发 ValueError?

MongoDB 聚合 - $sum 参数