How to insert ISODate(DateTime) to mongodb with c#

I have one class.

I adding class to mongodb.

but DateTime Properties as shows the string

c#

public class FRM_FORMREQUEST
{
    public int ORACLE_ID { get; set; }
    public string FORMNUMBER { get; set; }
    public string COMPANYCODE { get; set; }
    public DateTime? RECORDDATE { get; set; }
    public string RECORDUSER { get; set; }
}

mongodb record

{
"_id" : ObjectId("56927dfc249d951f1031f526"),
"ORACLE_ID" : 771653,
"FORMNUMBER" : "4992014309217",
"COMPANYCODE" : "499",
"RECORDDATE" : "2014-08-21T19:35:27",
"RECORDUSER" : "parttime35"
}

Business

 var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(FRM_FORMREQUEST);



 MongoDB.Bson.BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(jsonData);


 frmFormCollection.Insert(document);

I want insert like Date

thanks for all help.

Upvotes: 0

Views: 3594

Answers (1)

Peter
Peter

Reputation: 12711

The problem is that you're serializing it to JSON using Json.Net, which will write the dates as strings in the ISO 8601 standard format by default. Then you're de-serializing it to a BsonDocument using the BsonSerializer, which (unless you give it any other instructions) will just assume those are strings.

I have to ask, why jump through these hoops? Why not just let the driver serialize your object for you when you call Insert()?

collection.Insert(FRM_FORMREQUEST);

Or, if you have to work with a BsonDocument, use the mongo BsonSerializer to convert your object directly (instead of converting it to Json first).

var document = FRM_FORMREQUEST.ToBson();
collection.Insert(document);

Upvotes: 2

Related Questions