首先,我对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. Problem (Iterate over all collections)
有没有可能变成这样.
var my_collections = show collections;
my_collections.forEach(function(current_collection){
print(current_collection);
});
问题是,my_collections
分的作业(job)不起作用.
2. Problem (storing collection in 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:在src/mongo/shell/query处为false.js:124
最后一个元素似乎没有正确保存.
关于我做错了什么有什么建议吗??
UPDATE
尼尔的回答 bootstrap 我找到了这个解决方案.除了他的代码,我还必须判断getTimestamp
函数是否真的存在.对于一些"虚拟"Collection ,似乎没有_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)")
}
}
});