srdemart
srdemart

Reputation: 59

How to update multiple changes to doc with embedded docs in MongoDB using official C# driver

I want to update various fields on various levels deep within the document and apply all the changes with one call. Ideally, the driver would traverse the object model with the models.Save(model) and identify changes, but this appears to have no affect on changes made 2 levels deep in the graph.

So, I'm now trying to update the entire doc with this approach and it doesn't have an affect. Any idea on what the correct syntax would be?

var models = _database.GetCollection<Model>("Models");
var modelQuery = Query.EQ("_id", new ObjectId("4dfa2601dc1c791d40106a25"));
var model = models.FindOneAs<Model>(modelQuery);

// Apply various changes (including embedded docs)...
var dataRef = model.Objects.Find(Domain.Object.Reference);
dataRef.Set(Domain.Field.Reference.Name, "Some Ref Name");

models.Update(modelQuery, Update.Set("_id", BsonDocumentWrapper.Create(model)));

Upvotes: 0

Views: 257

Answers (1)

kheya
kheya

Reputation: 7612

There is a limitation on the level of depth you can traverse and do update in current mongodb.

Consider this blog post example:

Post{
  comments{
    replies{
      voters:["bob","steve"]
    }
  }
}

You can't update voters array as it is deeper than 2 levels even with a $ operator. The solution is to create a separate collection for comments. I am referring to v 1.8

Hope this helps.

Upvotes: 1

Related Questions