Skip to content

Instantly share code, notes, and snippets.

@dlee148
Last active May 13, 2020 15:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dlee148/a0ec830baff5c71471213616f22cb902 to your computer and use it in GitHub Desktop.
Save dlee148/a0ec830baff5c71471213616f22cb902 to your computer and use it in GitHub Desktop.
Workaround for updating nested objects using the MongoDB C# driver. The driver does not support multiple positional operators in one statement, making multi-level schema tedious to use.
public static void EditNested(string collectionName, string primaryKey, string secondaryKey, string tertiaryKey,
ArrayList parameters, PropertyInfo[] fields)
{
var collection = Mongo.Connect(out _client, out _database, collectionName);
var filter = Builders<BsonDocument>.Filter.Eq(someField, primaryKey);
var result = BsonSerializer.Deserialize<SomeType>(collection.Find(filter).First());
int index1 = 0, index2 = 0;
for (int i = 0; i < result.EmbeddedArray.Length; i++)
{
if (result.EmbeddedArray[i].SomeProperty == secondaryKey)
{
index1 = i;
break;
}
}
for (int j = 0; j < result.EmbeddedArray[index1].DeeplyEmbeddedArray.Length; j++)
{
if (result.EmbeddedArray[index1].DeeplyEmbeddedArray[j].SomeOtherProperty == tertiaryKey)
{
index2 = j;
break;
}
}
var changeList = new List<UpdateDefinition<BsonDocument>>();
for (int i = 0; i < fields.Length; i++)
{
changeList.Add(Builders<BsonDocument>.Update.Set("EmbeddedArray." + index1 +
".DeeplyEmbeddedArray." + index2 + "." + fields[i].Name, parameters[i]));
}
var update = Builders<BsonDocument>.Update.Combine(changeList);
collection.UpdateOne(filter, update);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment