Created
November 5, 2014 00:33
-
-
Save icalvo/e9b1588fbf84bc32e891 to your computer and use it in GitHub Desktop.
MongoDB: Recreate documents with new Id (e.g. change Id type)
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
/// <summary> | |
/// For each document of a collection, remove it and add it again with a new | |
/// Id generated by a provided function. | |
/// </summary> | |
/// <param name="connectionString">MongoClient connection string.</param> | |
/// <param name="databaseName">The database name</param> | |
/// <param name="collectionName">The collection name.</param> | |
/// <param name="idFunction">The Id generation function.</param> | |
/// <returns>List of concern results.</returns> | |
public static IEnumerable<WriteConcernResult> MigrateIds( | |
string connectionString, | |
string databaseName, | |
string collectionName, | |
Func<BsonDocument, BsonValue> idFunction) | |
{ | |
MongoClient client = new MongoClient(connectionString); | |
MongoServer server = client.GetServer(); | |
MongoDatabase database = server.GetDatabase(databaseName); | |
MongoCollection<BsonDocument> entryCollection = database.GetCollection(collectionName); | |
foreach (BsonDocument entry in entryCollection.FindAll()) | |
{ | |
yield return entryCollection.Remove(Query.EQ("_id", entry["_id"])); | |
entry.Set("_id", idFunction(entry)); | |
yield return entryCollection.Save(entry); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment