mongodb c# driver current server time

1,506 views
Skip to first unread message

Pavel

unread,
Jun 6, 2016, 7:25:44 PM6/6/16
to mongodb-user
Hi All, 
Does anybody know how to get current server time using mongodb c# driver?

Wan Bachtiar

unread,
Jun 15, 2016, 3:43:35 AM6/15/16
to mongodb-user

Hi Pavel,

Have you tried using C# system DateTime Structure to get current time ?
For example, you could utilise UtcNow:

var database = client.GetDatabase("databaseName");
var collection = database.GetCollection<BsonDocument>("collectionName");
var newDocument = new BsonDocument { { "timestamp", DateTime.UtcNow} };
collection.InsertOne(newDocument);

Which should generate a document below in MongoDB:

{ "_id" : ObjectId("5761046d18bbc402248650a1"), "timestamp" : ISODate("2016-06-15T07:31:57.235Z") }

The snippet above is for MongoDB Driver v2.2.x and MongoDB 3.2.x.

If this does not answer your question, could you share details on what you are trying to achieve ?

Kind regards,

Wan.

Shukhrat Nekbaev

unread,
Aug 16, 2016, 8:53:37 PM8/16/16
to mongodb-user
Hi Wan,

I think he wanted to get time on the database server using c# driver. However, I could extend this question and ask how to use $currentDate using c# driver. Basically I want Mongo to update DateCreated property by setting it to the current server time upon insert. I'm using strongly typed collections.

John Murphy

unread,
Aug 19, 2016, 8:19:44 AM8/19/16
to mongodb-user

I think he wanted to get time on the database server using c# driver.

Here is a way to get the current server time using the MongoDB C# driver. Note that the user must have rights to perform the serverStatus command. There may be a performance cost with running this command so do not call it frequently.

var db = mongoClient.GetDatabase("admin");
var serverStatusCmd = new BsonDocumentCommand<BsonDocument>(new BsonDocument { { "serverStatus", 1 } });
var result = db.RunCommand(serverStatusCmd);
var localTime = result["localTime"].ToLocalTime();

However, I could extend this question and ask how to use $currentDate using c# driver. Basically I want Mongo to update DateCreated property by setting it to the current server time upon insert. I’m using strongly typed collections.

$currentDate is an update operator which means you cannot use it when performing an insert.

You can however use an update with upsert set to true. This will create a new document and set CreatedDate to the server time, so long as no document matches the update query criteria.

We have feature request SERVER-13695 opened to add $currentDate expression support for insert. Be sure to add your vote if it is something you would like to see.

Regards,

John Murphy

Reply all
Reply to author
Forward
0 new messages