'Mongo C# Driver and ObjectID JSON String Format

Is it possible to force the JsonWriterSettings to output the ObjectID as

{ "id" : "522100a417b86c8254fd4a06" }

instead of

{ "_id" : { "$oid" : "522100a417b86c8254fd4a06" }

I know I could write my own parser, but for the sake of code maintenance, I would like to find away to possibly override the Mongo JsonWriterSettings.

If this is possible, what classes/Interfaces should I override?



Solution 1:[1]

If you're OK with using MongoDB C# attributes or the Mapper, then you can do something like this:

public class Order {
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
}

That way, you can refer to the type as a string normally (including serialization), but when MongoDB serializes it, etc., it's internally treated as an ObjectId. Here's using the class map technique:

BsonClassMap.RegisterClassMap<Order>(cm => {
    cm.AutoMap();
    cm.SetIdMember(cm.GetMemberMap(c => c.Id);
    cm.GetMemberMap(c => c.Id)
       .SetRepresentation(BsonType.ObjectId);
});

Solution 2:[2]

If you use JSON.NET instead it's easy to add a JsonConverter that converts ObjectId values to strings and vice-versa.

In ASP.NET WebAPI you can then add this to the default set of converters at Formatters.JsonFormatter.SerializerSettings.Converters

Solution 3:[3]

I am using MongoDB.Driver with version 2.15.1 and for me is working this simple solution:

public class Order {
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
}

You do not have to specify attribute [BsonId] if the property name is "Id" The driver uses naming conventions.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 WiredPrairie
Solution 2 Ian Mercer
Solution 3 Petr Å tipek