I\'m using MongoDB via the official C# driver with an ASP.NET MVC web site.
I have the following C# model:
public class Contact
{
public ObjectId Id
as @Louie Almeda suggests, i think the best approach is with the BsonTypeMapper.MapToDotNetValue. BsonTypeMapperOptions can be customized too.
Here's what i'm using to convert a list on BsonDocument to a json string using LINQ and newtonsoft serializer :
var jsonString = JsonConvert.SerializeObject(bsonDocuments.ConvertAll(d => BsonTypeMapper.MapToDotNetValue(d)), Formatting.Indented)
var IDict = v as IDictionary<string, object>;
var dict = IDict.ToDictionary(x => x.Key, x => x.Value);
var dateVal = dict["$date"];
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var dateTimeVal = epoch.AddMilliseconds(Convert.ToDouble(dateVal));
I think you need to tweak your JSON serializer a bit more. Try this:
var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict };
Console.WriteLine(document.ToJson(jsonWriterSettings));
You SHOULD use JsonConvert
to properly convert the Date to Json. the accepted answer produces a date object like: { $date: 190012312211 }
as @Rick Strahl mentioned. This should work:
object val = BsonTypeMapper.MapToDotNetValue(bsonDocument);
string jsonString = JsonConvert.SerializeObject(val);
If the JSON data is safe for eval (since its coming from your server it probably is) then you can do like so. It's not particularly pretty, but it gets the job done.
http://jsfiddle.net/CVLhx/
var str = '{"_id" : ObjectId("52eaad4839b60812fca4bf28"),"Name": "Joe Blow","DateAdded" : ISODate("2014-01-30T19:51:35.977Z")}';
function ObjectId(id) { return id;}
function ISODate(d) {return d;}
var obj = eval('(' + str + ')');
console.log(obj);
I realize that I am very late to this party but I'll post an answer anyway in case somebody else comes along looking for a solution (as I did).
The trick is to let the Mongo db driver do the deserialization:
var collection = database.GetCollection<Contact>("collection name");
var contact = collection.Find(Query.EQ("Name", "Joe Blow"));
Now contact
will have the expected values.