使用pymongo返回ObjectID的.str [英] Return .str of ObjectID using pymongo

查看:231
本文介绍了使用pymongo返回ObjectID的.str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用pymongo仅返回BSON ObjectId的字符串部分。通过从bson.objectid导入ObjectId,我可以将字符串编码为Object id;

How would I return just the string component of an BSON ObjectId using pymongo. I'm able to encode a string into an Object id by importing ObjectId from bson.objectid; but am unable to do the reverse.

当我尝试:

for post in db.votes.find({'user_id':userQuery['_id']}):
            posts += post['_id'].str

我得到的ObjectId没有属性str错误。

I get an ObjectId has no attribute str error.

谢谢!

推荐答案

python中获取对象的字符串表示形式的标准方法是使用 str 内置函数:

The standard way in python to get object's string representation is using the str builtin function:

id = bson.objectid.ObjectId()
str(id)
=> '5190666674d3cc747cc12e61'

这篇关于使用pymongo返回ObjectID的.str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆