문제

I clearly don't understand how I update / insert a subdocument in an existing document. I tried the following:

        query = aCollection.find_one({stuffToFind})
        aCollection.update(query,
                      {"$set": {"subDoc" : {"1" : String, "2" : datetime.datetime.now(), "3" : otherString}}})

this only works one time but I want to constantly change the subDoc's Data 1,2 and 3 if this code is executed. find_and_modify also fails, because it seems to overwrite the whole document deleting all other fields but the id and those specified in update. Since I'm pretty new to MongoDB it would be nice if someone could give me a code example how to figure out my problem.

Edit: without the "$set" statement it remains unchanged as well on a second execution..

Edit2: this seems to work, eventhough I'm unable to edit the affected (JSON)document directly in MonjaDB anymore :D

aCollection.update(query(but this time not as a variable),
                      {"$set" : {"subDoc.1" : Sting, "subDoc.2" : datetime.datetime.now(), "subDoc.3" : otherString}})

I dont know, why this is working so maybe someone could explain what I did wrong..

Thanks in advance,

Codehai

도움이 되었습니까?

해결책

The query you supply to update in the first example is not correct, instead of:

query = aCollection.find_one({stuffToFind})

you should have:

query = {stuffToFind}

The reason that the update does not throw an error is that the result of find_one is a dictionary. Note also that sometimes the above will even work since in the update you are actually asking MongoDB to match the whole document that corresponds to the initial query. Subsequent uses of query of course in that case will not bring the expected results since the document will have been changed from the update.

The $set updates only the keys that we specify leaving everything else untouched. That means that if we update an embedded object then the whole embedded object will get replaced with what we specify in $set. If we want to pinpoint keys in the embedded object we must use dot notation as you do in the second example.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top