C# updating document array item

I’ve seen a lot of solutions relating to updating a document array but nothing seems to work. I need to change the first item of an array (dosage) to a new value (newdosage) in C#

I specify the document I want to update:
filter = Builders.Filter.Eq("_id", new ObjectId(Key));

I try to create an update query:
first try: var update = Builders.Update.Set( f => f.dosage[-1], newdosage);
This doesn’t work because the dosage property is not known in a BsonDocument

second try: var update = Builders.Update.Set(x => x.Dosage[-1], newdosage);
This is recognized to be a valid assignment so I try to execute: collection.UpdateOne(filter, update);

collection is assigned and the database would be accessed fine except UpdateOne requires
the second parameter to be of BsonDocument type.

I’ve tried numerous other solutions but nothing works. Can anyone help:
Thanks.

Try Builders<BsonDocument>.Filter... and Builders<BsonDocument>.Update...

Quick Start: C# and MongoDB - Update Operations | MongoDB

also check Update Arrays in a Document — Node.js (mongodb.com)

The C# starters guide always gives examples of filtering on array elements before an update but in this case the array elements are unknown data or complex objects. Their positioning examles using $ don’t work in C#.
The problem is clear in this example of array insertion:

set up ‘collection’ to access data base, then:
var filter = Builders.Filter.Eq(Keys.MongoId, ObjectId.Parse(chatRoomId));
var update = Builders.Update.PushEach(Keys.Comments, new List() { comment }, position: 0);
collection.UpdateOne(filter, update);

This gives a C# syntax error because filter and update are not created as ‘Builders…’
There are many “solutions” that seem to get around C# typing in the mongodb update calls.

if you haven’t found it yet, will you also check this: Indexed_Positional_Typed

the file belongs to a test file of UpdateDefinitionBuilderTests.cs of the driver and seems to do the thing you are trying.

every “test” file in the repo is also an example of that feature so much so that even documentation points to these files for examples. again, if you haven’t been there before, you will find that useful.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.