用pymongo在mongodb中按ObjectId搜索


82

我需要使用pymongo用python搜索ObjectId,但是我总是会收到此错误。有什么想法如何搜索?

import pymongo
from pymongo import MongoClient
from pymongo import ObjectId

gate = collection.find({'_id': ObjectId(modem["dis_imei"])})
print gate

    Traceback (most recent call last):
  File "C:\Users\gerswin\Documents\Proyectos\Demonio py\test.py", line 2, in <module>
    import pymongo
  File "C:\Python27\lib\site-packages\pymongo\__init__.py", line 80, in <module>
    from pymongo.connection import Connection
  File "C:\Python27\lib\site-packages\pymongo\connection.py", line 39, in <module>
    from pymongo.mongo_client import MongoClient
  File "C:\Python27\lib\site-packages\pymongo\mongo_client.py", line 45, in <module>
    from pymongo import (auth,
  File "C:\Python27\lib\site-packages\pymongo\database.py", line 22, in <module>
    from pymongo.collection import Collection
  File "C:\Python27\lib\site-packages\pymongo\collection.py", line 25, in <module>
    from pymongo.cursor import Cursor
  File "C:\Python27\lib\site-packages\pymongo\cursor.py", line 19, in <module>
    from bson import RE_TYPE
ImportError: cannot import name RE_TYPE

1
pymongo是什么版本?
Evgenii

我的版本是pymongo == 2.5
Gerswin Lee

Answers:


162

我使用pymongo 2.4.1。

from bson.objectid import ObjectId
[i for i in dbm.neo_nodes.find({"_id": ObjectId(obj_id_to_find)})]

我将pymongo更新为2.5-一切正常。您可以看到错误消息和您的代码吗?
Evgenii

@GerswinLee注意到“来自bson.objectid”吗?在2.5版中尝试从pymongo导入时会出现导入错误。您需要python-bson软件包。我不确定pymongo是否已安装。
hyprnick

为了使它正常工作,我不得不obj_id_to_find变成一个字符串,即str(obj_id_to_find)
luke
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.