Take the 2-minute tour ×

I'm having an issue with saving and retrieving dates with Mongo using the c# driver. For some reason it it's truncating the ticks.

When I store this:

DateTime -> 5/17/2011 7:59:13 PM 
Ticks -> 634412591533741650

I get this back:

Ticks -> 634412591533740000

So if I try to do:

serverDateTime == mongoDateTime

It always fails. Anyway around this?

share|improve this question
If you don't care about milliseconds precistion in your comparison, instead of serverDateTime == mongoDateTime you could do Math.Abs((serverDateTime - mongoDateTime).TotalMilliseconds < 1000 –  Bala R May 17 '11 at 20:20
That's good enough but way too verbose to have to do everywhere. I suppose I could do it as an extension method. Any idea why that happens though? –  Micah May 17 '11 at 20:22
@Bala R 1 tick = 1 ten-millionth of a second, so I think you mean if all you care about is milliseconds. e.g. Math.Abs((serverDateTime - mongoDateTime).TotalMilliseconds) < 1. –  Conrad Frix May 17 '11 at 20:26
@Conrad my logic was to ignore any diff under a second. I didn't consider the ticks, just the fact that 1000ms = 1s. –  Bala R May 17 '11 at 20:36
@Bala R. Oh I see. I guess I had ticks in my head from the question –  Conrad Frix May 17 '11 at 20:38
show 3 more comments

2 Answers

up vote 9 down vote accepted

The reason is that the BSON DateTime format stores values with less precision than a .NET DateTime value, so when you read it back from the database the value has been truncated.

If your DateTime value is a property of a C# class you are serializing you can ask the serializer to serialize the DateTime value as an embedded document containing both the BSON DateTime value (truncated) and the original .NET DateTime value (stored as Ticks). In that case the value will not be truncated when deserialized.

For example:

public class MyClass {
    public ObjectId Id;
    public DateTime MyDateTime;

You can also use a BsonRepresentation of Int64 or String and not lose precision, but then the stored document only has Ticks or a string representation and no BSON DateTime, which makes it hard to do DateTime related queries.

You'll also want to keep in mind that DateTime values are stored in UTC in the database. The best practice is to always use UTC values for storage and only use local times when displaying them to the user.

share|improve this answer
Thanks for the tip. I'm going to store it as a datetime but use @Bala R's extension method for comparison. –  Micah May 24 '11 at 12:34
add comment

Here's an extension you could use :)

public static class MongoDateComparison
    private static int precisionInMilliseconds = 1000;
    public static bool  MongoEquals(this DateTime dateTime, DateTime mongoDateTime)
        return Math.Abs((dateTime - mongoDateTime).TotalMilliseconds) < precisionInMilliseconds;
share|improve this answer
add comment

Your Answer


