6

How does javascript forEach() function work in mongodb shell?

With what sequence are the documents being processed?

Eg, let's say that I have two big collections and those two collections should contain the same number of documents (note that the structure of the document isn't necessarily the same), and I want to iterate the first and see if for each document in the first collection, there's a record for it in the second collection :

db.MyColl.find().forEach(
    function(aDocument) { 
        print("Checking :"+aDocument._MyId)
        var db2 = db.getSiblingDB("mySiblingDb");
        var aDocument2 = db2.MyColl.findOne({_MyId: aDocument._MyId});    
        if (aDocument2 == null) { 
           print("Missing document with _MyId: " + aDocument._MyId);
        }  
    }
);

Is this piece of code going to iterate the documents with the same sequence?

Dimitrios
  • 445
  • 1
  • 4
  • 14
  • What do you mean by "iterate the documents with the same sequence"? Your code looks like it does a `find()` on one collection (collection `A`), then tries to `findOne()` the corresponding matching document on the second collection (collection `B`). There is only one iteration in the code, and that is inside the `forEach()`. I guess I'm not understanding your intent here. Are you asking about the ordering of the sequence that will be processed by the `forEach()`? – kevinadi Jul 27 '18 at 00:08

1 Answers1

0
db.collection.find(query).forEach(function(err, doc) {
  // ...
});

Foreach return error function as first and document as second argument

thatcoder
  • 367
  • 2
  • 9