rlib rlib - 7 months ago 34
Bash Question

Iterating over array in series in mongodb shell

I need to iterate over array inside mongoshell with the aid of async library in the following way:

load('/opt/kif/crons/dashboard/node_modules/async/lib/async.js');
async.series([
function(cb) { print("First"); cb(null,1); },
function(cb) { print("Second"); cb(null,2); },
function(cb) { print("Third"); cb(null,3); }
], function(err, res) {
printjson(res);
});


and running

mongo testasync.js


which returns

MongoDB shell version: 3.2.0
connecting to: test
First
2016-05-01T15:41:45.589+0000 E QUERY [thread1] ReferenceError: setTimeout is not defined :
_delay<@/opt/kif/crons/dashboard/node_modules/async/lib/async.js:196:9
async.eachOfSeries/iterate/<@/opt/kif/crons/dashboard/node_modules/async/lib/async.js:272:29
only_once/<@/opt/kif/crons/dashboard/node_modules/async/lib/async.js:44:13
_parallel/</<@/opt/kif/crons/dashboard/node_modules/async/lib/async.js:723:17
_restParam/<@/opt/kif/crons/dashboard/node_modules/async/lib/async.js:167:1
@testasync.js:3:33
_parallel/<@/opt/kif/crons/dashboard/node_modules/async/lib/async.js:718:1
iterate@/opt/kif/crons/dashboard/node_modules/async/lib/async.js:262:1
async.eachOfSeries@/opt/kif/crons/dashboard/node_modules/async/lib/async.js:281:9
_parallel@/opt/kif/crons/dashboard/node_modules/async/lib/async.js:717:1
async.series@/opt/kif/crons/dashboard/node_modules/async/lib/async.js:739:9
@testasync.js:2:1

failed to load: testasync.js
[root@NQPC002 dashboard]#


How do I do that?

Answer

While the MongoDB shell uses JavaScript, its database access methods are all synchronous so a sequence of calls is already performed serially.

So a method like db.collection.update directly returns a WriteResult instead of using a callback.

Comments