pymongo数据库

时间:2018-07-23 22:43:06

标签: python mongodb python-2.7 pymongo

pymongo中遇到了一个真正的路障错误,这使我无法继续进行项目。我已经搜索过此案例,但其他类似的帖子及其答案对我却不起作用。

首先,我正在跑步:

mongod v3.6.5-2-g9b2264cf14    
MongoDB shell version v3.6.5-2-g9b2264cf14

这是我的最小工作/错误产生示例:

myname@myhost ~ $ /usr/bin/python
Python 2.7.12 (default, Dec  4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> db = pymongo.MongoClient("localhost:27017")
>>> db.testcollection.insert({"foo": "bar"})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/pymongo/collection.py", line 2344, in __call__
    self.__name)
TypeError: 'Collection' object is not callable. If you meant to call the 'insert' method on a 'Database' object it is failing because no such method exists.
>>>

其他StackOverflow主题建议改用insert_one()。但是,这对我产生了相同的结果:

myname@myhost ~ $ /usr/bin/python
Python 2.7.12 (default, Dec  4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> db = pymongo.MongoClient("localhost:27017")
>>> db.testcollection.insert_one({"foo": "bar"})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/pymongo/collection.py", line 2344, in __call__
    self.__name)
TypeError: 'Collection' object is not callable. If you meant to call the 'insert_one' method on a 'Database' object it is failing because no such method exists.

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您尚未选择数据库。 “ db”对象是MongoClient对象。您需要获取数据库对象。

尝试一下:

db[<database-name>][<collectin-name>].insert(<document>);

答案 1 :(得分:0)

尝试:

import pymongo
client = pymongo.MongoClient()
db = client[ "test" ] # makes a test database called "test"
collection = db[ "test" ] #makes a collection called "test" in the "test" db
collection.insert_one( {"foo" : "bar" }) #add a document