首先,我对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)")
        }
    }
});

推荐答案

有一个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()英镑的支票,以满足可能出现的空账.

Mongodb相关问答推荐

Go mongo-驱动程序测试,FindOne未根据给定的筛选器返回正确结果

为什么我的Mongoose更新找不到匹配?

Mongo 聚合将 $sort 与 $geoNear 结合使用

如何为具有相同名称的嵌套字段创建文本索引

MongoDB shell:如何删除列表以外的所有集合

在MongoDb的数组中计算大于某个数字的数字

MongoDB 到 Snowflake 连续加载

当属性确实存在时,为什么mongoose模型的 hasOwnProperty 返回 false?

如何将 json 字符串编组到 bson 文档以写入 MongoDB?

Stripe:必须提供来源或客户

在 MongoDB 中创建简短、唯一的对象 ID

MongoDB - 投影一个并不总是存在的字段

带有排序功能的mongoose findOne

Mongoose 不创建新集合

MongoDB - 我如何找到另一个集合中的文档未引用的所有文档

MongoDB 范围查询中 $lt 和 $gt 的顺序

mongodb 的计数性能

在 MongoDB 上使用 $push 更新数组时避免重复值

Mongoose:Model.create 和 Collection.insert 有什么区别

有没有办法执行更新操作的dry run?