When faced with two nested cursor.forEach()
functions or a while
loop, the second one doesn't seem to be executed. The issue arises when attempting to remove duplicates from a vast collection by transferring documents to another collection and checking for existing duplicates using the following code in the mongo shell:
var fromColl = db.from.find(),
toColl;
fromColl.forEach(function(fromObj){
toColl = db.to.find({name: fromObj.name});
if (toColl.length() == 0) {
//no duplicates found in the target collection, insert
db.to.insert(fromObj);
} else {
//possible duplicates found in the target collection
print('possible duplicates: ' + toColl.length());
toColl.forEach(function(toObj){
if (equal(fromObj.data, toObj.data)) {
//duplicate...
}
});
}
});
Although toColl.length()
is printed in the else block, the second forEach loop fails to execute. Any idea why this might be happening?