0

suppose i have data like this

{
 _id: '14577543',
 items: [
      { x: 0, y: 0, z: 0 }
      { x: 0, y: 0, z: 0 }
      { x: 0, y: 0, z: 0 }
      { x: 0, y: 0, z: 0 }
   ]
}

How can i update let say 2nd item of document's array field (items) in Mongodb C# driver ? i don't want the way of doing this in Mongo Javascript wrapper. I just want to know the right syntax. How can i do that?

1

1 Answer 1

0

In order to update an element of an array object, you'll have to retrieve the array object (items) first, update it and then save it back. Following should get you to do what you need.

// This is not a correct formatted objectID but to show you how it 'would' work
var filter = Builders<ClassObject>.Filter.Eq(x => x._id, ObjectId("14577543")); 
var data = collection.Find(filter).FirstOrDefault();
var element = data.items.ElementAt(1); // 0 indexed.
element.y = 2;
element.x = 5;

collection.FindOneAndUpdate<ClassObject>(
    x => x._id == ObjectId("15477543"), 
    Builders<ClassObject>.Update.Set(ri => ri.items, data.items),
    new FindOneAndUpdateOptions<ClassObject, ClassObject>() { IsUpsert = true }
);
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.