使用 Python 使用字符串查询 MongoDB 的 _id 的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7846001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the correct way to query MongoDB for _id using string by using Python?
提问by MFB
I am using pymongo driver. Supposedly, one can use a string to query the _id field of a document, like this:
我正在使用 pymongo 驱动程序。据说,可以使用字符串来查询文档的 _id 字段,如下所示:
thing = db.things.find_one({'_id':'4ea113d6b684853c8e000001'})
But it doesn't work. What am I doing wrong?
但它不起作用。我究竟做错了什么?
回答by DhruvPathak
It should be :
它应该是 :
from pymongo.objectid import ObjectId
thing = db.things.find_one({'_id': ObjectId('4ea113d6b684853c8e000001') })
EDIT:
The current import is:
from bson.objectid import ObjectId
编辑:当前的导入是:
from bson.objectid import ObjectId
回答by Sean
PyMongo has changed its structure. ObjectID
is no longer imported from pymongo
, but from bson
. It should now be:
PyMongo 已经改变了它的结构。ObjectID
不再从 导入pymongo
,而是从bson
. 现在应该是:
from bson.objectid import ObjectId
thing = db.things.find_one({'_id': ObjectId('4ea113d6b684853c8e000001')})
As a reminder, per pypi/pymongo, do not install the “bson” package. PyMongo comes with its own bson package; doing “pip install bson” installs a third-party package that is incompatible with PyMongo.
提醒一下,对于pypi/pymongo,不要安装“bson”包。PyMongo 自带 bson 包;执行“pip install bson”会安装与 PyMongo 不兼容的第三方包。
回答by Jigyasu Tailor
To print it:
要打印它:
import pymongo
from bson.objectid import ObjectId
print(db.things.find_one({'_id': ObjectId('4ea113d6b684853c8e000001')}))
if you don't want to print, store in other variable
如果您不想打印,请存储在其他变量中
回答by lobster1234
thing = db.things.find_one({'_id':ObjectId('4ea113d6b684853c8e000001')})
should work
thing = db.things.find_one({'_id':ObjectId('4ea113d6b684853c8e000001')})
应该管用
回答by Karthik Gomadam
PyMongo documentation does not seem to be in sync with the current version. ObjectIds are now under bson.objectid namespace. If I remember right, they have been that way since version 2.3. Use from bson.objectid import ObjectId.
PyMongo 文档似乎与当前版本不同步。ObjectIds 现在在 bson.objectid 命名空间下。如果我没记错的话,它们从 2.3 版开始就是这样。使用 from bson.objectid 导入 ObjectId。