c# – Update Mongodb em array

Question:

{
    "_id" : "55dcb404478e7227203d3a65",
    "Nome" : "Grupo Familia",
    "Pessoas" : [ 
        {
            "PessoaId" : "55dcb425478e72207833e970",
            "Nome" : "Carlos",
            "Habilidades" : [
                {
                    "HabilidadeId" : "55dcb433478e7229b0e3ee07",
                    "Valor" : 20,
                    "Nome": "José"
                },
                {
                    "HabilidadeId" : "55dcb425478e72207833e961",
                    "Valor" : 40,
                    "Nome" : "Vitor"
                }
            ],
        }
    ],
}

Using mongocsharpdriver , how do I update the modify type (without using save) in the Abilities Array ? I got a way to do it but I need the array's index , but I don't know how to find it. In the example below I passed the index as 0, then it takes the first person and adds the new skill:

var novaHabilidade = new Habilidade { };
var update = Update<Grupo>.AddToSet(a => a.Pessoas[0].Habilidades, novaHabilidade);
context.Grupos.Update(Query.EQ("_id", "55dcacb7478e722a60e7c002"), update);

I tried it in a different way, trying to filter the person I want:

var update = Update<Grupo>.AddToSet(a => a.Pessoas.Find(b => b.PessoaId == "55dcb425478e72207833e970").Habilidades, novaHabilidade);

Not successful, gives error "Object reference not instantiated". Does anyone know a way to do it? I wanted to use the objects I created, nothing to create BsonDocument .

This is the error "Unable to determine the serialization information for the expression" is giving

Answer:

I found out how to do it, if anyone is interested, follow:

var update = Update.AddToSet("Pessoas.$.Habilidades", novaHabilidade.ToBsonDocument());
var retorno = context.Grupos.Update(Query.EQ("Pessoas.PessoaId", new ObjectId("55de157b478e72231cfeca69")), update);
Scroll to Top
AllEscort