title: Insert data in mongodb using javascript loop
body: <p>I want to insert data in a mongodb collection with a javascript loop.
  Here is my code :</p>
  
  <pre><code>var collection = db.DATA.find();
  
  for (var i = 0; i &lt; 3; i++) {
          db.PARSED_DATA.insert(collection[i].folders);
  }
  </code></pre>
  
  <p>I have the error :</p>
  
  <blockquote>
    <p>2017-08-04T10:17:06.390+0200 E QUERY    [thread1] TypeError: collection[i] is undefined :
    @(shell):2:9</p>
  </blockquote>
  
  <p>When i execute in mongodb shell the commands :</p>
  
  <pre><code>var collection = db.DATA.find();
  db.PARSED_DATA.insert(collection[0].folders);
  db.PARSED_DATA.insert(collection[1].folders);
  db.PARSED_DATA.insert(collection[2].folders);
  </code></pre>
  
  <p>I have the expected result and i still don't uderstand why my for loop doesn't work.</p>
  
  <p>EDIT :
  When i execute this inside Robo 3T i get the expected result :</p>
  
  <pre><code>var collection = db.DATA.find().toArray();
  
  for (var i = 0; i &lt; 3; i++) {
          db.PARSED_DATA.insert(collection[i].folders);
  }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/7s3vM.png" rel="nofollow noreferrer">Result in Robo 3T</a></p>
  
  <p>But when i execute it inside my bash code with</p>
  
  <pre><code>mongo &lt;myip&gt;:27017 &lt; db_parse.js
  </code></pre>
  
  <p>I get the error again</p>