28

首先,我对 mongodb 很陌生。这是我的问题,我无法找到解决方案。

假设我有 3 个不同的集合。

mongos> show collections
collectionA
collectionB
collectionC

我想创建一个脚本来迭代这个数据库中的所有集合,并在每个集合中找到最后插入的时间戳。这是在 mongos 中有效的方法。

var last_element = db.collectionA.find().sort({_id:-1}).limit(1);
printjson(last_element.next()._id.getTimestamp());
ISODate("2014-08-28T06:45:47Z")

1. 问题(遍历所有集合)

有没有可能做某事。喜欢。

var my_collections = show collections;
my_collections.forEach(function(current_collection){
    print(current_collection);
});

问题在这里,分配my_collections不起作用。我明白了SyntaxError: Unexpected identifier。我需要引用“显示”声明吗?甚至可能吗?

2.问题(在js var中存储集合)

我可以通过这样做来解决问题 1:

var my_collections = ["collectionA", "collectionB", "collectionC"];
my_collections.forEach(function(current_collection){
    var last_element = db.current_collection.find().sort({_id:-1}).limit(1);
    print(current_collection);
    printjson(last_element.next()._id.getTimestamp());
});

产生以下last_element.next()错误:

错误 hasNext: false 在 src/mongo/shell/query.js:124

似乎 last_element 没有正确保存。

关于我做错了什么的任何建议?


更新

尼尔斯的回答让我找到了这个解决方案。除了他的代码之外,我还必须检查该函数是否getTimestamp真的存在。对于某些“虚拟”集合,似乎没有 _id 属性。

db.getCollectionNames().forEach(function(collname) {
    var last_element = db[collname].find().sort({_id:-1}).limit(1);
    if(last_element.hasNext()){
        var next = last_element.next();
        if(next._id !== undefined && typeof next._id.getTimestamp == 'function'){
           printjson(collname + " >> "+next._id.getTimestamp());
        }else{
          print(collname + " undefined!! (getTimestamp N/A)")
        }
    }
});
4

1 回答 1

52

有一个db.getCollectionNames()帮助方法可以为您执行此操作。然后,您可以实现您的代码:

db.getCollectionNames().forEach(function(collname) {
    // find the last item in a collection
    var last_element = db[collname].find().sort({_id:-1}).limit(1);
    // check that it's not empty
    if (last_element.hasNext()) {
        // print its timestamp
        printjson(last_element.next()._id.getTimestamp());
    }
})

您可能还想.hasNext()在那里办理登机手续,以应对可能的空集合。

于 2014-08-28T07:55:39.260 回答