2

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

Albert Lazaro de Lara
  • 2,540
  • 6
  • 26
  • 41
Juzzbott
  • 1,737
  • 2
  • 25
  • 44
  • 1
    Possible duplicate of [How to use MongoDB's Postional Operator in C# code?](http://stackoverflow.com/questions/9382685/how-to-use-mongodbs-postional-operator-in-c-sharp-code) – Blakes Seven Mar 02 '16 at 03:08
  • Yep, that question is what I was looking for... I wasn't aware the term was Positional Operator. So I can't use Linq for the $ positional value. Cheers. – Juzzbott Mar 02 '16 at 03:22

1 Answers1

2

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

Juzzbott
  • 1,737
  • 2
  • 25
  • 44