0

I can't seem to figure out the exact set of statements that are needed to update an entire element of an array. This is what I have currently:

//id, gameId, updatedGame passed in
var client = mongoContext.Clients.FindOne( Query<Client>.EQ(x => x.Id, id));
var index = client.Games.FindIndex(x => x.Id == gamedId);
var update = Update<Client>.Set(x => x.Games[index], updatedGame);
var query = Query<Client>.EQ(x => x.Id, client.Id);
mongoContext.Clients.Update(query, update);
mongoContext.Clients.Save(client);

I can do this in javascript, but unfortunately I'm working in C# at the moment. Thanks for any help.

2
  • What error are you getting? Commented Aug 19, 2014 at 3:10
  • I was not getting any error. It just silently failed. Commented Aug 19, 2014 at 23:18

1 Answer 1

1

The Update() statement you are using is more suited for bulk updates. In this case you only need to update one record so all you need is the Save() function. Also, without knowing the code behind mongoContext there are only certain things we can help with. Your object looks like it was adopted as a mixture between EF Code First and the mongo syntax. Anyway, here is how I've accomplished something very simular:

MongoCollection<Reported> collection = GetCollection();
Reported report = collection.FindOneById(Id);
report.IsReviewed = true;
collection.Save(report);

By using the FindOneById() function mongo returns a copy of your object with it's ObjectId. Which means all subsequent changes to that object will be updated when you pass it back to the Save() function. In your case, changing your array value would be done in where I set report.IsReviewed = true;

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

1 Comment

That did work. I just updated the actual array element.

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.