Search code examples
mongodbmongodb-.net-driver

mongodb insert creation time separated from objectId


I am using mongodb with the official c# driver.

I am using Guids as Id field for my objects. I don't want to introduce a dependency on the mongodb bson classes so I am not using ObjectId in my domain layer.

Is it possible to instruct mongodb to insert a creation timestamp into objects that I insert into the datastore?

Example:

public class Foo
{
    public Guid Id {get;set;}
    public DateTime CreatedOn {get;set;}
}

Using mongodb idGenerators I can get the Guids generated upon insert. I know ObjectId has the timestamp included but as mentioned I wouldn't want my class to look like this

public class Foo
{
    public ObjectId Id { get; set; }
    public DateTime CreatedOn {get { return Id.CreationTime;}}
}

Solution

  • You can have an _id which is itself a document :

    in json : { _id : {guid : ...., createdOn : ....} , field1 : ..., field2:....}
    

    You just have to modify your idGenerator to have this behavior.

    I recommend, however, that you really re-consider to use ObjectId.