为什么这个Mongo查询在循环中没有返回任何内容,但是循环的主体有效?

时间:2015-03-06 01:22:29

标签: mongodb

如果我在mongo shell中运行以下查询,我得到的是一堆打印到屏幕上的空数组:

for (c in collections) {printjson(db.getCollection(c).find().limit(1).toArray())  }

其中collections是当前db中所有集合的列表。但是,如果我只是说:

printjson(db.getCollection(collections[0]).find().limit(1).toArray()) 

我将json文档打印到屏幕上。

为什么我在mongo shell中看到这种行为?

1 个答案:

答案 0 :(得分:2)

for...in循环中,ccollections的当前索引,而不是数组元素。

因此,您需要将其更改为:

for (c in collections) { printjson(db.getCollection(collections[c]).find().limit(1).toArray())  }