简体   繁体   English

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

[英]Python / Pymongo variable for collection name in db insert command

I have this small piece of code that basically takes a list and runs a loop, running search queries against twitter, for each item in the list. 我有一小段代码,基本上需要一个列表并运行一个循环,针对twitter运行搜索查询,列表中的每个项目。 I want each item in the list to be a collection name but for some reason I can't figure out how to make db<collection_name_variable>.insert(post)> to actually work: 我希望列表中的每个项目都是集合名称,但由于某种原因,我无法弄清楚如何使db<collection_name_variable>.insert(post)>实际工作:

I get an error: 我收到一个错误:

TypeError: unsupported operand type(s) for +: 'Database' and 'str' TypeError:+不支持的操作数类型:''数据库'和'str'

I know this is probably very basic but I am just learning. 我知道这可能是非常基本但我只是在学习。

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

Replace: 更换:

insert = db + nosql + ".insert(post)"
insert

with: 有:

db[nosql].insert(post)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM