Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Convention to automatically persist string identifiers as ObjectId's in MongoDB.
using System.Diagnostics;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Driver;
namespace ConsoleApplication1
class Program
private class Foo
public string Id { get; set; }
static void Main(string[] args)
var pack = new ConventionPack();
pack.Add(new StringObjectIdConvention());
ConventionRegistry.Register("MyConventions", pack, _ => true);
// just to prove it works...
var client = new MongoClient();
var testDb = client.GetServer().GetDatabase("test");
var fooCol = testDb.GetCollection<Foo>("foo");
fooCol.Save(new Foo());
var fooColBson = testDb.GetCollection("foo");
var fooDoc = fooColBson.FindOne();
private class StringObjectIdConvention : ConventionBase, IPostProcessingConvention
public void PostProcess(BsonClassMap classMap)
var idMap = classMap.IdMemberMap;
if (idMap != null && idMap.MemberName == "Id" && idMap.MemberType == typeof(string))
idMap.SetIdGenerator(new StringObjectIdGenerator());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment