I am trying to write a migration script between an older version and the newer version of a model, we have a reactive migration system which checks loaded models version to see if its up to date. If not it will apply a migration delta to the model and persist it back in its new form. In this new version all that has changed is that now one of the child objects has a key called i.e "SomeNewKey".
So here is how the data looks for the old version of the model:
{
SomeModel:
{
_id: <some-guid>,
Version: 1.0.1
Name: <some-string>,
SomeArrayData: [
{
Name: <some-string>,
DateCreated: <some-date>
},
{
Name: <some-string>,
DateCreated: <some-date>
},
{
Name: <some-string>,
DateCreated: <some-date>
}
]
}
}
And here is how it should be for the new version:
{
SomeModel:
{
_id: <some-guid>,
Versio: 1.0.2
Name: <some-string>,
SomeArrayData: [
{
Name: <some-string>,
DateCreated: <some-date>,
SomeNewKey: <some-default-guid>
},
{
Name: <some-string>,
DateCreated: <some-date>,
SomeNewKey: <some-default-guid>
},
{
Name: <some-string>,
DateCreated: <some-date>,
SomeNewKey: <some-default-guid>
}
]
}
}
So as you can see I basically need to get the model, then go through each sub document in SomeArrayData
and insert a new key with a default empty guid.
I first of all tried:
var findQuery = Query.EQ("_id", id);
var updateQuery = Update.Set("SomeArrayData.SomeNewKey", Guid.Empty);
var result = collection.Update(findQuery, updateQuery, UpdateFlags.Multi);
if (result.Ok == false) { throw new Exception(result.ErrorMessage); }
However this kept blowing up on the write concern, and I couldn't find out much about that, so then I looked round and found articles like:
Updating an array of objects with a new key in mongoDB
Which seem to imply I need to do an aggregate call to do an unwind of the arrays, but I cannot find any examples of how to do this sort of thing in the C# driver, so can anyone point me in the right direction?