Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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())
    });
like image 341
Igor Pashchuk Avatar asked Aug 16 '11 19:08

Igor Pashchuk


People also ask

How is datetime stored in MongoDB?

MongoDB will store date and time information using UTC internally, but can easily convert to other timezones at time of retrieval as needed.

In which format date is stored in MongoDB?

Internally, Date objects are stored as a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970).

What is timestamp in MongoDB?

Timestamps. BSON has a special timestamp type for internal MongoDB use and is not associated with the regular Date type. This internal timestamp type is a 64 bit value where: the most significant 32 bits are a time_t value (seconds since the Unix epoch)

How do I find the latest collection in MongoDB?

To find last object in collection, at first sort() to sort the values. Use limit() to get number of values i.e. if you want only the last object, then use limit(1).


1 Answers

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;
}
like image 92
Chris Fulstow Avatar answered Oct 14 '22 14:10

Chris Fulstow