Search code examples
c#mongodbmongodb-.net-driver

how to use $currentdate in mongodb using C# drivers


I am trying to write below query for updating time with the server-side time in C#.

db.users.update(
    { _id: 1 },
    {
        $currentDate:
        {
            lastModified: true,
            lastModifiedTS: { $type: "timestamp" }
        }
    })

Could anyone please suggest how to run this command through C# code and which driver version do I need to use for this?


Solution

  • Almost a year later I stumbled upon this question to do the same and did a little research.

    I found this interesting way in version 1.9.2 of the official mongo driver:

    var query = Query.EQ("_id", 1);
    var update = Update
       .Set("field_timestamp_local", DateTime.Now)
       .CurrentDate("field_timestamp_mongo");
    collection.Update(query, update);
    

    This code sets 2 fields to a timestamp, the first the local clients timestamp, and the second field to the server time.