Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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:

I get an error:

TypeError: unsupported operand type(s) for +: 'Database' and '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
like image 761
Brian Carpio Avatar asked Apr 02 '12 16:04

Brian Carpio


People also ask

How do you insert using PyMongo?

To insert a record, or document as it is called in MongoDB, into a collection, we use the insert_one() method. The first parameter of the insert_one() method is a dictionary containing the name(s) and value(s) of each field in the document you want to insert.

How do you update a collection in PyMongo?

Update Collection You can update a record, or document as it is called in MongoDB, by using the update_one() method. The first parameter of the update_one() method is a query object defining which document to update. Note: If the query finds more than one record, only the first occurrence is updated.


1 Answers

Replace:

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

with:

db[nosql].insert(post)
like image 196
diliop Avatar answered Sep 21 '22 15:09

diliop