Reputation: 34297
I have the need to update a subdocument in Mongo, and this is how I did it. This screenshot shows what my documents look like. And the code below it shows how I updated Geddy’s name and instrument.
Note: This approach was taken from this SO post:
var update = Update.Set("Members.$.Instrument", "Keyboards").Set("Members.$.LastName", "Leex");
var collection = MongoDbHelper.Db.GetCollection<Band>("Bands");
collection.Update(Query.And(Query.EQ("Name", "Rush"), Query.EQ("Members.FirstName", "Geddy")), update);
Is there another/better way to do this that makes use of strongly-typed properties instead of all of these string literals?
Upvotes: 1
Views: 1089
Reputation: 12187
There is currently no support for writing queries or updates like this one (i.e. querying against individual subfields of arrays and using "$" in the update) using the typed builders.
The difficulty is coming up with expressions that compile without errors and yet express the desired intent correctly.
For example, the following might be a workable design, but using -1 as an index value is kind of hacky:
var query = Query.And(
Query<Band>.EQ(b => b.Name == "Rush"),
Query<Band>.EQ(b => b.Members[-1].FirstName == "Geddy"));
var update = Update<Band>
.Set(b => b.Members[-1].Instrument, "Keyboards")
.Set(b => b.Members[-1].LastName, "Leex");
Note: this is just a possible design for supporting "$" in typed builders. It is not actually implemented this way.
If you have any ideas for how a type safe version of this could be expressed you should create a JIRA ticket suggesting the feature.
Upvotes: 2