Update in array MONGODB

3
{
"_id" : "55dcb404478e7227203d3a65",
"Nome" : "Grupo Familia",
"Pessoas" : [ 
    {
        "PessoaId" : "55dcb425478e72207833e970",
        "Nome" : "Carlos",
        "Habilidades" : [
            {
                "HabilidadeId" : "55dcb433478e7229b0e3ee07",
                "Nome": "Pular",
                "Macetes": [
                        {"Descricao" : "Usar um tênis macio"},
                        {"Descricao" : "Se alongar"}
                ]
            },
            {
                "HabilidadeId" : "55dcb425478e72207833e961",
                "Nome" : "Correr"
            }
        ],
    }
],

}

I have this collection in the mongo and to with the following doubt: How do I add a new mallet in the "run" ability?

    
asked by anonymous 27.08.2015 / 21:59

2 answers

1

You should use $addToSet or $push . The difference is whether you want unique elements in the array or not.

There is a positional operator $ that you can use to update elements in the index that matches your query. So if you "know" that there is a skill, but you do not know your position, you should do the following query:

db.grupos.update({ _id: "...", "Pessoas.Habilidades.Nome": "Correr" }, {
  "$addToSet": {
    "Pessoas.$.Habilidades.$.Macetes": { /*...*/ }  
  }
})

If you want to remove elements, you will have to use $pull and to add / remove more than one element you will have to use $each .

Useful links:

I suggest an index in Pessoas.Habilidades.Nome .

EDIT

I just researched a little more and what you want to do is not possible:

From the documentation:

  The positional operator $ can not be used for searches that traverse more than one array, such as searches that run through "arrays" in other arrays, because substitution by placeholder $ is a single value

It is necessary to change the way the data is modeled. Or lose the atomicity of the operation.

    
31.08.2015 / 16:01
0

You can use $ set . Example:

db.bla.update({"_id":"55dcb404478e7227203d3a65"},
{
    "$set": {
        "Pessoas.0.Habilidades.1.Macetes": [
            {
                "HabilidadeId": "idnovo",
                "Nome": "Pular"
            }
        ]
    }
})
    
27.08.2015 / 22:16