user3732901
user3732901

Reputation: 1

How to Update a Sub Child in mongodb using C#

public class Parent
    {
        [BsonId]
        public string Id { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public List<Child> Children { get; set; }
    }

    public class Child
    {
        [BsonId]
        public string Id { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public List<Pet> Pets { get; set; }
    }

    public class Pet
    {
        [BsonId]
        public string Id { get; set; }
        public string Name { get; set; }
    }

Inserting the collection with child and Pet

Parent parent = new Parent() { Id = ObjectId.GenerateNewId().ToString(), };

        List<Child> children = new List<Child>();
        List<Pet> pets = new List<Pet>();

        children.Add(new Child()
        {
            Id = ObjectId.GenerateNewId().ToString(),
            Firstname = "Child",
            Lastname = "One"
        });
        children.Add(new Child()
        {
            Id = ObjectId.GenerateNewId().ToString(),
            Firstname = "Child",
            Lastname = "Two"
        });
        pets.Add(new Pet() { Id = ObjectId.GenerateNewId().ToString(), Name = "Fishy" });

        parent.Children = children;
        parent.Children[0].Pets = pets;



        collection.Insert(parent);

After Inserting how can I update the name of the pet to doggy ????

Upvotes: 0

Views: 1098

Answers (1)

FLCL
FLCL

Reputation: 2514

Unfortunately, as described there, MongoDb does not provide the feature you need. It's very sad for document-oriented database, as I think(but it may be appear in the next versions).

So the only why is to load document and update them like this:

var res = col.Find(Query.ElemMatch("Children.Pets", Query.EQ("Name", "Fishy")));
foreach(var _parent in res)
{
    foreach (var _child in _parent.Children)
    {
        var pets = _child.Pets;
        if(pets!=null)
        {
             var pet = pets.FirstOrDefault(x => x.Name == "Fishy");
             if(pet!=null)
                 pet.Name = "Doggy";
        }
    }
    col.Save(_parent);
}

Upvotes: 1

Related Questions