如何获取使用 MongoDB C# 驱动程序创建 MongoDB 集合的日期?
我需要迭代 MongoDB 数据库中的所有集合并获取创建每个集合的时间(我知道我可以获取集合中每个对象的时间戳,但如果存在更简单/更快的方法)。
这应该让您了解我正在尝试做什么:
MongoDatabase _database;
// code elided
var result = _database.GetAllCollectionNames().Select(collectionName =>
{
_database.GetCollection( collectionName ) //.{GetCreatedDate())
});
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())
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
据我所知,MongoDB 不跟踪集合创建日期。然而,自己做这件事真的很容易。添加一个简单的方法,如下所示,并在创建新集合时使用它:
然后,每当您需要信息时,只需查询
collectionMetadata
集合即可。或者,如果您想使用示例中的扩展方法,请执行以下操作: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:
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:“创建日期”不是集合元数据的一部分。集合不“知道”它何时创建。有些索引有一个
ObjectId()
,它暗示着一个时间戳,但这并不一致且不可靠。因此,我不相信这是可以做到的。
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.
就像盖茨副总裁说的,没有办法使用元数据......但你可以获取集合中最旧的文档并从 _id 中获取它。
此外,您可以为此目的在集合中插入“空”文档,而无需重复维护另一个集合。
而且很容易获得最旧的文档:
old = db.collection.find({}, {_id}).sort({_id: 1}).limit(1)
dat = old._id.getTimestamp()
默认情况下,所有集合都有一个基于
_id
字段的索引,使得find
高效。(我使用MongoDb 3.6)
Like Mr. Gates VP say, there is no way using the metadata... but you can get the oldest document in the collection and get it from the _id.
Moreover, you can insert an "empty" document in the collection for that purpose without recurring to maintain another collection.
And it's very easy get the oldest document:
old = db.collection.find({}, {_id}).sort({_id: 1}).limit(1)
dat = old._id.getTimestamp()
By default, all collection has an index over
_id
field, making thefind
efficient.(I using MongoDb 3.6)
看起来像是一些死后的帖子,但无论如何:我试图找到答案并得到了它:
在 Mongo shell 中检查了它,不知道如何在 C# 中使用:
Seems like it's some necroposting but anyway: I tried to find an answer and got it:
Checked it in Mongo shell, don't know how to use in C#: