Update Mongodb in array

Asked

Viewed 199 times

3

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

Using the mongocsharpdriver, how do I give update type modify (without using save) no Array of Skills ? I got a way to do it but I need the index of array, but I don’t know how to find it. In the example below I passed the index like 0, then he 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 differently, trying to filter out the person I want:

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

I did not succeed, it gives the error of "Reference of object not instantiated". Does anyone know a way to do? I wanted to use the objects I created, no creating BsonDocument.

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

  • 1

    First of all, you tested whether this returns value? a.Pessoas.Find(b => b.PessoaId == "55dcb425478e72207833e970")

  • I think you can’t use everything in one line. This error is well known, and it happens when lib tries to mount the expression and can’t. Better separate into more lines.

  • @How would you do this operation that I’m trying to do ?

  • @Gustavogoiscardoso I’ll put as an answer. Incidentally, I think you need to learn how to use the site. See how here.

  • In fact, if I put it as an answer, it will be in classical syntax. This object Update<T> I’ve never seen it. I don’t even know how it works.

  • can be in classical syntax !

Show 1 more comment

1 answer

1

I figured out how to do it, in case anyone’s interested follow:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.