Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo C# Driver and ObjectID JSON String Format

Tags:

json

c#

mongodb

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?

like image 824
user19055 Avatar asked Sep 03 '13 16:09

user19055


People also ask

What is Mongo C?

The MongoDB C Driver, also known as “libmongoc”, is a library for using MongoDB from C applications, and for writing MongoDB drivers in higher-level languages. It depends on libbson to generate and parse BSON documents, the native data format of MongoDB.

What is a Mongo driver?

The official MongoDB Node. js driver allows Node. js applications to connect to MongoDB and work with data. The driver features an asynchronous API which allows you to interact with MongoDB using Promises or via traditional callbacks.

How do I download MongoDB drivers?

Open-Source MongoDb JDBC DriverThe driver binaries can be downloaded as zip file, which you should uncompress. Download the zip, unpack and include the jar files in your classpath. The driver is compatible with Java 11. for any issues with the driver, you can write to us.


1 Answers

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);
});
like image 98
WiredPrairie Avatar answered Sep 29 '22 13:09

WiredPrairie