如何获取使用MongoDB C#驱动程序创建MongoDB集合的日期? [英] How do I get the date a MongoDB collection was created using MongoDB C# driver?

查看:148
本文介绍了如何获取使用MongoDB C#驱动程序创建MongoDB集合的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历MongoDB数据库中的所有集合,并获取创建每个集合的时间(我知道我可以获取集合中每个对象的时间戳,但是我不想这样做路由(如果存在更简单/更快的方法).

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

推荐答案

据我所知,MongoDB不会跟踪集合创建的日期.但是,自己完成此操作确实很容易.添加一个类似这样的简单方法,并在创建新集合时使用它:

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

然后,每当需要信息时,只需查询collectionMetadata集合.或者,如果您想使用示例中的扩展方法,请执行以下操作:

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

这篇关于如何获取使用MongoDB C#驱动程序创建MongoDB集合的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆