Question

I asked myself, whether javascript (concerning mongoDB) waits for the execution of mongoDB processes.

For example:

Im inserting documents like

for (i=0; i<=myarray.length -1; i++)
{
        db.mycol.insert(myarray[i]);
}

If I check the col status directly after that only see a few documents in the db or even 0. (e.g. instead of 100 only 29 or 0). When I execute the sleep() function with e.g. sleep(10000) I can see all may inserted documents.

So my question is, how can I make sure, that javascript waits for the complete insert? Or how can I measure that? At the moment I'm using

start = new Date().getTime();

for (i=0; i<=myarray.length -1; i++)
{
        db.mycol.insert(myarray[i]);
}
end = new Date().getTime();
time = end - start;

But if the insert-process isn't completed, the measurement of that function seems senseless to me.

edit:

by using db.getLastError({w:1});

I receive to following error:

uncaught exception: getlasterror failed: { "singleShard" : "replica2/ip:port,ip:port", "n" : 0, "lastOp" : NumberLong("5824731790958395692"), "connectionId" : 111744, "assertion" : "wrong type for field (w) 3 != 2", "assertionCode" : 13111, "errmsg" : "db assertion failure", "ok" : 0 } failed to load: ... myscript.js

Was it helpful?

Solution

If you want to wait until MongoDB has written the data you can call getLastError with whatever options you're looking to wait for.

Like this:

start = new Date().getTime();
for (i=0; i<=myarray.length -1; i++) {
    db.mycol.insert(myarray[i]);
}
db.getLastError({w:1});
end = new Date().getTime();
time = end - start;

OTHER TIPS

try this: db.getLastError({w: majority});

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top