Search code examples
pythonmongodbcollectionsdocuments

How to update all documents in a collection with same key but different values?


I have 10 documents in a collection:

>> {'_id':0, 'self':{....}} {'_id':1,'self':{....}} ........ {'_id':9,'self':{....}}

now I want to update all documents with their count, which means after the updating, the documents will look like:

>> {'_id':0, 'count':0, 'self':{....}} {'_id':1,'count':1, 'self':{....}} ........ {'_id':9,'count':9,'self':{....}}

I know there is a update({},{'$set':{}}) method but I don't know how to use this to update different values for each document. Does anyone know some fast methods to do this?


Solution

  • for index,each in enumerate(myCollection.find({})):
        each["count"] = index
        id = each["_id"]
        each.pop("_id", None)
        collection.update({"_id":id},{"$set":each},upsert=True)
    

    Note : documents are un-ordered in a collection as mentioned by @Michael