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

社会主义新天地 提交于 2019-11-30 09:19:04

问题


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())
    });

回答1:


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;
}



回答2:


The "creation date" is not part of the collection's metadata. A collection does not "know" when it was created. Some indexes have an ObjectId() which implies a timestamp, but this is not consistent and not reliable.

Therefore, I don't believe this can be done.



来源:https://stackoverflow.com/questions/7083943/how-do-i-get-the-date-a-mongodb-collection-was-created-using-mongodb-c-sharp-dri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!