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.
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