Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot update document in PyMongo

Tags:

python

pymongo

I have code in Python/PyMongo like ( code should simulate inner join and all documents from second collection to put (nest inside) in list and add to first appropriate document in Mongo). Idea is to load two collections and pass two fields ( name of fields for connection ) and all documents from second collection with same attribute like in first put in list and add to appropriate document in first collection .

(For example in first collection I have documents with fileds "country","population" and in second I have "country" and "car factories" and I want to put ( denormalize ) first collection list of all factories for appropriate country)

    for f in first_collection_records:
        temp=[]
        id=f['_id']
        second_collection_records.rewind()
        for s in second_collection_records:
            if f[field_one]==s[field_two]:
                temp.append(s)
        f[self.__second_collection_name__]=temp
        first_collection_records.update({"_id":id}, f, safe=True)

but I got error 'Cursor' object has no attribute 'update'. What I done wrong ?

like image 704
Damir Avatar asked Apr 28 '26 12:04

Damir


1 Answers

first_collection_records is a pymongo.cursor.Cursor object. It's the result you get when you call db.first_collection.find(). You need to call update on your original collection object:

# assuming your query looked something like this
first_collection_records = db.first_collection.find()

# your code here....

# your last line should reference the collection object to do the update
db.first_collection.update({"_id":id}, f, safe=True)
like image 55
Mark Gemmill Avatar answered Apr 30 '26 02:04

Mark Gemmill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!