Last active
May 13, 2020 15:52
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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