我想在没有数字键(_id)的 mongoDB 集合上执行迭代。集合只有随机字符串作为_id,并且集合的大小很大,因此使用RAM加载整个文档.toArray()不是一个可行的选择。加上我想对每个元素执行异步任务。的使用.map()或者.each(),.forEach()是因为任务的异步性质的限制。我尝试使用上述方法运行任务,但它当然与异步任务冲突,返回未决的承诺而不是正确的结果。
例子
async function dbanalyze(){
let cursor = db.collection('randomcollection').find()
for(;;){
const el = cursor.hasNext() ? loaded.next() : null;
if(!cursor) break
await performAnalyze(cursor) // <---- this doesn't return a document but just a cursor object
}
}
Run Code Online (Sandbox Code Playgroud)
如何仅使用 mongoDB 集合迭代for()?