遍历所有Mongo集合并执行查询

cb0*_*cb0 21 javascript mongodb mongo-shell mongodb-query

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

假设我有3个不同的收藏品.

mongos> show collections
collectionA
collectionB
collectionC
Run Code Online (Sandbox Code Playgroud)

我想创建一个脚本,遍历此数据库中的所有集合,并在每个集合中查找最后插入的时间戳.这是在mongos里面有效的方法.

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

1.问题(迭代所有集合)

是否有任何可能性...... 喜欢.

var my_collections = show collections;
my_collections.forEach(function(current_collection){
    print(current_collection);
});
Run Code Online (Sandbox Code Playgroud)

问题在这里,分配my_collections不起作用.我得到SyntaxError: Unexpected identifier.我需要引用'show'声明吗?它甚至可能吗?

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());
});
Run Code Online (Sandbox Code Playgroud)

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

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

似乎last_element未正确保存.

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


UPDATE

尼尔斯回答了我的解决方案.除了他的代码,我还要检查函数是否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)")
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

Nei*_*unn 41

有一个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());
    }
})
Run Code Online (Sandbox Code Playgroud)

您可能还需要.hasNext()在那里检查以满足可能的空集合.