db insert命令中的集合名称的Python/Pymongo变量

Bri*_*pio 4 python mongodb pymongo

我有一小段代码,基本上需要一个列表并运行一个循环,针对twitter运行搜索查询,列表中的每个项目.我希望列表中的每个项目都是一个集合名称,但由于某种原因,我无法弄清楚如何db<collection_name_variable>.insert(post)>实际工作:

我收到一个错误:

TypeError:+不支持的操作数类型:''数据库'和'str'

我知道这可能是非常基本但我只是在学习.

from twython import Twython
from pymongo import *

conn = Connection('localhost')
db = conn.nosqltweets
twitter = Twython()

types = ['mongodb', 'cassandra', 'couchdb']

for nosql in types:
    search_results = twitter.searchTwitter(q=nosql, rpp="100")
    for tweet in search_results["results"]:
        from_user = tweet['from_user'].encode('utf-8')
        text = tweet['text']
        created_at = tweet['created_at']
        id_str = tweet['id_str']
        post = { 'id_str': id_str, 'from_user': from_user, 'created_at': created_at }
        insert = db + nosql + ".insert(post)"
        insert
Run Code Online (Sandbox Code Playgroud)

dil*_*iop 11

更换:

insert = db + nosql + ".insert(post)"
insert
Run Code Online (Sandbox Code Playgroud)

有:

db[nosql].insert(post)
Run Code Online (Sandbox Code Playgroud)

  • 除非上面的代码中缺少某些内容,否则这应该可行.db的类型为`<class'pymongo.database.Database'>`并且您可以使用点符号,即`db.couchdb`或`dict`成员访问,即`db ['couchdb']`来获取`的实例<class'pymongo.collection.Collection'>`,你可以在其上调用`insert()`. (3认同)