Search code examples
mongodbmongodb-.net-driver

How do I get the date a MongoDB collection was created using MongoDB C# driver?


I need to iterate through all of the collections in my MongoDB database and get the time when each of the collections was created (I understand that I could get the timestamp of each object in the collection, but I would rather not go that route if a simpler/faster method exists).

This should give you an idea of what I'm trying to do:

MongoDatabase _database;
// code elided
var result = _database.GetAllCollectionNames().Select(collectionName =>
    {
        _database.GetCollection( collectionName ) //.{GetCreatedDate())
    });

Solution

  • As far as I know, MongoDB doesn't keep track of collection creation dates. However, it's really easy to do this yourself. Add a simple method, something like this, and use it whenever you create a new collection:

    public static void CreateCollectionWithMetadata(string collectionName)
    {
        var result = _db.CreateCollection(collectionName);
        if (result.Ok)
        {
            var collectionMetadata = _db.GetCollection("collectionMetadata");
            collectionMetadata.Insert(new { Id = collectionName, Created = DateTime.Now });
        }
    }
    

    Then whenever you need the information just query the collectionMetadata collection. Or, if you want to use an extension method like in your example, do something like this:

    public static DateTime GetCreatedDate(this MongoCollection collection)
    {
        var collectionMetadata = _db.GetCollection("collectionMetadata");
        var metadata = collectionMetadata.FindOneById(collection.Name);
        var created = metadata["Created"].AsDateTime;
        return created;
    }