MongoDb .NET to replace string in array using ElemMatch()

1 day ago 3
ARTICLE AD BOX

I'm using the MongoDb .NET driver (v3.7) to replace string in array using ElemMatch to match the array string element.

All examples I see regarding ElemMatch() involve matching an object in an array (or list) of objects.

Can I not use the same methods to target a string within an array?

For example, I want to replace round with triangle and tried the following code, thinking the positional operator would find/reference the string in the array that needed changing. But perhaps that is not possible with arrays of primitives?

var idFilter = Builders<Sample>.Filter.Eq(d => d.Id, "000000000000000000001002"); var elemMatchFilter = Builders<Sample>.Filter.ElemMatch(x => x.MyStringArray, "round"); var filtersAnded = Builders<Sample>.Filter.And(idFilter, elemMatchFilter); var update = Builders<Sample>.Update.Set("MyStringArray.[$]", "triangle"); UpdateResult result = collection.UpdateOne(filtersAnded, update);

This results in an exception:

JSON reader was expecting a value but found 'round'.

Data model:

internal class Sample { [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } = ObjectId.GenerateNewId().ToString(); public int[] MyIntArray { get; set; } = []; public string[] MyStringArray { get; set; } = []; }

Code to generate 2 documents:

public const string Samples = "Samples"; IMongoDatabase? iMongoDatabase = mongoClient.GetDatabase("UpdateArraysTesting"); iMongoDatabase.CreateCollection(Samples); SamplesCollection = iMongoDatabase!.GetCollection<Sample>(Samples); Sample sample = new() { Id = "000000000000000000001001", MyIntArray = new int[] { 10, 15 }, MyStringArray = new string[] {"square","box" } }; SamplesCollection.InsertOne(sample); sample = new() { Id = "000000000000000000001002", MyIntArray = new int[] { 22, 27 }, MyStringArray = new string[] { "round", "ball" } }; SamplesCollection.InsertOne(sample);
Read Entire Article