首先,我对 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 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());
});
The last_element.next()
产生以下错误:
错误 hasNext: false 在 src/mongo/shell/query.js: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)")
}
}
});