Compare against current server date

264 views
Skip to first unread message

TM

unread,
Mar 19, 2012, 12:06:53 PM3/19/12
to mongodb-csharp
Hi,

is is possible to compare against the current server date and time in
an query? In SQL Server I would use getdate() or now() in mysql.

As I use the mongo shell very rarly I think I have to use something
like this :

db.Guest.find({Bday:{$lt:new Date()}})

How would I write the query in C#?

Thanks!

Sam Martin

unread,
Mar 19, 2012, 12:20:03 PM3/19/12
to mongodb...@googlegroups.com
Query.Lte("dt", DateTime.Now)

You can still execute the JavaScript equiv using BsonDocument too.

Sam Martin

Sam Martin

unread,
Mar 19, 2012, 12:25:07 PM3/19/12
to mongodb...@googlegroups.com
Sorry, forgot the find bit (from ipad not easy)

var query = Query.LTE("BDay", DateTime.Now);
foreach (BsonDocument guest in guests.Find(query)) {
    // do something with guest
}

TM

unread,
Mar 20, 2012, 2:44:47 AM3/20/12
to mongodb-csharp
Thanks for the reply, but this would compare to the time on my
application server, but I want to compare the time against the time on
the mongo cluster, which is synchronized AFAIK.

Is the BsonDocument the only chance to do this or is there a "native"
way?

On 19 Mrz., 17:25, Sam Martin <sambomar...@gmail.com> wrote:
> Sorry, forgot the find bit (from ipad not easy)
>
> var query = Query.LTE("BDay", DateTime.Now);
> foreach (BsonDocument guest in guests.Find(query)) {
>     // do something with guest}
>
>
>
>
>
>
>
> On Monday, March 19, 2012 4:20:03 PM UTC, Sam Martin wrote:
>
> > Query.Lte("dt", DateTime.Now)
>
> > You can still execute the JavaScript equiv using BsonDocument too.
>
> > Sam Martin
>

Robert Stam

unread,
Mar 20, 2012, 10:35:59 AM3/20/12
to mongodb...@googlegroups.com
Your easiest solution is to make sure the clocks are synchronized between your client machine and your server machine.

But if you must get the server's current time you can use:

    var serverDateTime = database.Eval("new Date()").AsDateTime;

Of course, by the time you get the reply from the server the DateTime is already a few milliseconds old!

Once you have fetched the current DateTime from the server you can use it to build queries.

    var query = Query.LT("Bday", serverDateTime);
    foreach (var document in collection.Find(query))
    {
        // process matching document
    }

Since this involves two round trips to the server (one to get the current time on the server, and another to process the query) I would recommend you keep the computers clocks synchronized and just use the client time. And be sure to do everything in UTC!
Reply all
Reply to author
Forward
0 new messages