简体   繁体   English

无法在PyMongo中更新文档

[英]Cannot update document in 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). 我有Python / PyMongo中的代码(代码应该模拟内连接和第二个集合中的所有文件放入(嵌入内部)列表中并添加到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) (例如在第1次收集中,我有文件“file”,“人口”,第2次有“国家”和“汽车工厂”,想把(正规化)所有工厂的第1个收集清单放在适当的国家)

    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'. 但是我收到错误'Cursor'对象没有属性'update'。 What I done wrong ? 我做错了什么?

first_collection_records is a pymongo.cursor.Cursor object. first_collection_records是一个pymongo.cursor.Cursor对象。 It's the result you get when you call db.first_collection.find() . 这是调用db.first_collection.find()时得到的结果。 You need to call update on your original collection object: 您需要在原始collection对象上调用update

# 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)

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

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