How insert an object inside a document using Pymongo?

时间:2017-04-10 01:39:56

标签: python mongodb pymongo

I'm using Pymongo to manipulate a collection witch has a structure that looks like the following:

{
    Client1:{
        "_id" : "Client1"
        Project1:{
            Software1:{
                language : "Python",
                complexity : "Low"
            }
            Software2:{
                language : "C#",
                complexity : "Low"
            }
            Software3:{
                language : "Java",
                complexity : "Hard"
            }
        }
    }
}

In this case, I tryed of many ways to Update the document Client1 inserting a new Software, but I could not find a way or function to do this.

So my question is: In this scope, how could I insert a new Software without exclude the existing items?

Here is what I was trying but didn't worked:

client = "Client1"
client = collection.find_one({"_id": client})

project = "Project1"

software = str(raw_input("Enter with the software to be added to project: "))

language = str(raw_input("Enter with the software language: "))

complexity = str(raw_input("Enter with the software complexity: "))

collection.update({"_id" : client["_id"], }, {"$set" : {
                                                            client[project] : {software : {"language": language, "complexity" : complexity}}
                                                        }
                                               })

The error that I got was: unhashable type: 'dict' in the line that contains client[project] : {software : {"language": language, "complexity" : complexity}}

Since now, thanks for your attention!

1 个答案:

答案 0 :(得分:0)

You're trying to use an unhashable variable to create a key in a dict. In this case, client[project] is a dict, and you are using that as a key in another dict. I think you just want your key to be project.

project : {software : {"language": language, "complexity" : complexity}}