C# .NET- GetTimeStamp in MongoDB using ObjectId
Today in this article, we will see how to get the time stamp using C# .NET- GetTimeStamp in MongoDB ID ObjectId.
Timestamp details could be useful for many other reasons and hence we will see how to get this timestamp.
ObjectId is the 12-byte element consisting of a timestamp value, a random value, and an incremental counter.
MongoDB _id field as ObjectId
MongoDB uses the _id field as ObjectId, this Id has few behavioral characteristics and it is explained below,
- MongoDB database automatically generates _id the field for insertion.
- This field is unique for every document inserted into the collection.
- _id field is automatically indexed and the index is unique.
A 4-byte timestamp is a UNIX timestamp. It represents the ObjectId’s creation timestamp, measured in seconds since the Unix epoch.
Getting started
Please create any C# .NET/.NET Core application.
Please add the MongoDB driver NuGet package using the Nuget Package manager,
PM> Install-Package MongoDB.Driver -Version 2.9.3
Note: Please use the latest driver available
Step I – Establish the connection to the Database using MongoDB driver,
var _mongoClient = new MongoClient("mongodb://your connection string"); var db = _mongoClient.GetDatabase("your database name");
If using ASP.NET Core, please use dependency injection for injecting the driver instance,
GetTimeStamp in MongoDB using ObjectId
var filter = Builders<BsonDocument>.Filter.Eq("_id",
(ObjectId)rootObject.GetElement("_id").Value);
ObjectId objMongoId = (ObjectId)rootObject.GetElement("_id").Value;
var creationDate = objMongoId .CreationTime;
ObjectId gives access to CreationTime, Increment Timestamp properties,
Please note that this timestamp is the timestamp of the document( for that id) when it was inserted the very first time in mongo collection.
References:
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.