相关疑难解决方法(0)

遍历所有Mongo集合并执行查询

首先,我对mongodb很新.这是我的问题,我无法找到解决方案.

假设我有3个不同的收藏品.

mongos> show collections
collectionA
collectionB
collectionC
Run Code Online (Sandbox Code Playgroud)

我想创建一个脚本,遍历此数据库中的所有集合,并在每个集合中查找最后插入的时间戳.这是在mongos里面有效的方法.

var last_element = db.collectionA.find().sort({_id:-1}).limit(1);
printjson(last_element.next()._id.getTimestamp());
ISODate("2014-08-28T06:45:47Z")
Run Code Online (Sandbox Code Playgroud)

1.问题(迭代所有集合)

是否有任何可能性...... 喜欢.

var my_collections = show collections;
my_collections.forEach(function(current_collection){
    print(current_collection);
});
Run Code Online (Sandbox Code Playgroud)

问题在这里,分配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());
});
Run Code Online (Sandbox Code Playgroud)

last_element.next()产生以下错误:

错误hasNext:在src/mongo/shell/query.js中为false: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 …
Run Code Online (Sandbox Code Playgroud)

javascript mongodb mongo-shell mongodb-query

21
推荐指数
1
解决办法
2万
查看次数

在MongoDB中获取文档而不指定集合

MongoDB ID对于单个数据库群集是唯一的.是否可以使用其ID来获取文档,而无需指定集合名称?

如果有,怎么样?

如果不是,为什么不呢?

database mongodb nosql

7
推荐指数
1
解决办法
3782
查看次数