循环遍历所有Mongo集合并执行查询。
循环遍历所有Mongo集合并执行查询。
首先,我对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。我需要引用'show'语句吗?这样做有可能吗?
2. 问题(将集合存储在js变量中)
我可以通过这样做解决问题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()产生以下错误:
error hasNext: false at src/mongo/shell/query.js:124
似乎last_element没有正确保存。
对于我做错了什么有什么建议吗??
更新
Neils的答案给我带来了这个解决方案。除了他的代码之外,我还必须检查函数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)")
}
}
});