The Blog of Ian Mercer.

MongoDB C# Driver - arrays, lists and hashsets

Here's a nice feature of the C# MongoDB driver: when you save .NET arrays, lists or Hashsets (essentially an IEnumerable<T>) to MongoDB you can retrieve it as any other IEnumerable<T>. This means you can migrate your business objects between these different representations without having to migrate anything in your database. It also means that any other language can access the same MongoDB database without needing to know anything about .NET data types.

For example, the following will all serialize to the same BSon data and any can be retrieved.

    public class Test1 
	{
	    [BsonId]
		public ObjectId Id { get; set; } 
    	public List<string> array { get; set; } 
	}

    public class Test2 
	{ 
		[BsonId]
		public ObjectId Id { get; set; } 
	    public string[] array { get; set; } 
	}

	public class Test3 
	{
		[BsonId]
		public ObjectId Id { get; set; }
		public HashSet array { get; set; } 
	}

Related Stories