Question

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?

Was it helpful?

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.

OTHER TIPS

Since $currentDate is a new feature of the upcoming 2.6 version, it might not be supported by your current driver. You could always use BSON documents instead of the strongly-typed wrappers to execute it:

collection.Update(
  new QueryDocument() { { "_id", 1 } }, 
  new UpdateDocument() { 
    { "$currentDate", new BsonDocument {
      { "lastModified", true },
      { "lastModifiedTS", new BsonDocument { { "$type", "timestamp" } } }
    } } 
  });

I assume the next version of the C# driver will support a strongly-typed helper for this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top