2

I'm using Python and Mongo for the fist time together and in documentation I wasn't able to find what I need.

So my data object looks like this

{
"_id" : ObjectId("54d372597d74523bc6991b9b"),
"id_user" : "2000001",
"date_registrated" : "2015-01-21 12:11:28.185",
"user" : "Bogdan",
"gender" : "M",
"email" : "a@a.com",
"charachters" : [ 
    {
        "quest_info" : "TUT_var,1421842359 STARTAREA,4 ",
        "char_name" : "Testarion"
    }
]
}

And I want to add new field into existing charachters, something like

party_user = {"party_name": "name",
               "admin": 0}

And finally I want to get this:

{
"_id" : ObjectId("54d372597d74523bc6991b9b"),
"id_user" : "2000001",
"date_registrated" : "2015-01-21 12:11:28.185",
"user" : "Bogdan",
"gender" : "M",
"email" : "a@a.com",
"charachters" : [ 
    {
        "quest_info" : "TUT_var,1421842359 STARTAREA,4 ",
        "char_name" : "Testarion"
        **"parties" : [{party 1},{party 2}]**
    }
]
}

The problem is how to create query that makes that ? I've tried with something like this but it failed miserably:

db.collection('MyDB').update(
                {"char_name": "Testarion"},
                {"$push": {
                    "charachters": {"parties": party_user}
                }})

I'm still new with Mongo and haven't catched up all the things but can you please show me what am I doing wrong ? Is that even possible ?

Community
  • 1
  • 1
T0plomj3r
  • 685
  • 1
  • 9
  • 23

1 Answers1

3

Use '$' in your update query for that array element:

db.collection.update(
   {"charachters.char_name": "Testarion"},
   {"$push": {"charachters.$.parties": "party_user"}})
anhlc
  • 13,839
  • 4
  • 33
  • 40