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

2
  • 1
    Possible duplicate of How to use MongoDB's Postional Operator in C# code? Commented Mar 2, 2016 at 3: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. Commented Mar 2, 2016 at 3:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.