Reputation: 1769
I'm trying to update a property of a specific object in an array in my document.
For example:
{
_id: #####
Items: [
{ Key: 1, Value: "Something" },
{ Key: 2, Value: "Foo" },
{ Key: 1, Value: "Bar" },
]
}
I'm using the MongoDB C# 2.0 driver, and this is what I have for my filter (although I'm pretty sure this will match the entire document, not the sub document).
FilterDefinition<GroupDto> filter = Builders<GroupDto>.Filter.Eq(i => i.Id, groupId) &
Builders<GroupDto>.Filter.ElemMatch(i => i.Items, u => u.Key == key);
Effectively, what I'm trying to achieve, is to match the document by Id, then find the object in the Items array where the 'Key' matches, and then update 'Value' property for that specific array object only. So I match Key: 2, I can update the 'Value' field for Key: 2 only, and Key: 1 and Key: 3 remain unchanged.
Is this even possible?
Cheers, Justin
Upvotes: 2
Views: 2940
Reputation: 1769
Actually, after reading the question posted, it's not quite a duplicate. In the example in the other question, the entire sub document is replaced, where as I just wanted to update a single field.
So I found the answer in a Jira ticket for the MongoDB CSHARP driver here: https://jira.mongodb.org/browse/CSHARP-531
You can use -1 in the indexer to specify using the positional operator.
From ticket:
This is only applicable to the new API in 2.0.0. -1 can be used as an indexer or with GetElementAt to indicate to us to use the positional operator. For example:
Builders<Entity>.Update.Set(x => x.MyArray[-1].Value, 10);
// will yield {$set: { "MyArray.$.Value", 10 } }
Cheers, Justin
Upvotes: 2