首先,我是新来的
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")
问题(迭代所有集合)
有什么可能的sth.喜欢.
var my_collections = show collections; my_collections.forEach(function(current_collection){ print(current_collection); });
在这里的问题,my_collections的作业不起作用.
我得到SyntaxError:意外的标识符.我需要引用’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()); });
last_element.next()产生以下错误:
error hasNext: false at src/mongo/shell/query.js:124
看来last_element没有正确保存.
关于我在做什么错误的任何建议?
UPDATE
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)") } } });
解决方法
有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()检查,以满足可能的空集合.
原文地址:https://www.jb51.cc/js/155219.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。