Skip to content

Instantly share code, notes, and snippets.

@icalvo
Created November 5, 2014 00:33
Show Gist options
  • Save icalvo/e9b1588fbf84bc32e891 to your computer and use it in GitHub Desktop.
Save icalvo/e9b1588fbf84bc32e891 to your computer and use it in GitHub Desktop.
MongoDB: Recreate documents with new Id (e.g. change Id type)
/// <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