I am using v2.9 of the MongoDB .NET Driver and want to use the ObjectId.getTimestamp() shell method. Is there any way to call this from my code in C#?
I have searched the Mongo SDK docs but have not found anything I can use.
Here is my sample model I am using with the Microsoft docs tutorial
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace WebApi.Models
{
public class Currency
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
// Need a CreatedAt getter that uses ObjectId.getTimestamp()
public string Name { get; set; }
public string IsoNumeric { get; set; }
public int MinorUnit { get; set; }
public string Symbol { get; set; }
public string SubUnit { get; set; }
}
}
After some random keyword auto-filling in my IDE I found the ObjectId class and it has a CreationTime getter -- http://mongodb.github.io/mongo-csharp-driver/2.9/apidocs/html/P_MongoDB_Bson_ObjectId_CreationTime.htm
In my class I added the following and it appears to work properly for what I need
[BsonIgnore]
public DateTime? CreatedAt => Id != null ? new ObjectId(Id).CreationTime : (DateTime?) null;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.