title: Mongo Script file - Export the execution result to CSV file after checking in two collections
body: <p>I want to export the result to CSV file after executing the script file using mongo shell.</p>
  <pre><code>topoList = db.collection1.aggregate([{
      $match: {
          equipments: {
              $elemMatch: {
                  &quot;identification&quot;: {
                      $exists: true;
                  }
              }
          }
      }
  }, {
      $unwind: &quot;$equipments&quot;
  }]);
  print(&quot;--- collection1 : load&quot; + topoList.length)
  while (topoList.hasNext()) {
      print(&quot;--- Inside while: load&quot;)
      topo_id = topoList.next().equipments
      
      while(topo_id.hasNext()){
          collection2_id = topo_id.next()._id
          print(&quot; *  &quot; + collection2_id)
      }
      print(&quot;- &quot; + topo_id)
      gatewayList = db.collection2.find({
          type: 'GATEWAY',
          collection1Id: topo_id
      }, {
          _id: 1
      })
      print(&quot;--- collection1 :&quot; + topo_id)
      db.collection1.find({
          _id: topo_id
      })
      print(&quot;---- collection2s&quot;)
      collection2sList = db.collection2.find({
          collection1Id: topo_id
      })
      while (collection2sList.hasNext()) {
          collection2_id = collection2sList.next()._id
          print(&quot; *  &quot; + collection2_id)
          db.collection2.find({
              _id: collection2_id
          })
      }
      print(&quot;----- end of collection1&quot;)
  }
  print(&quot;----- end of collection1&quot;)
  </code></pre>
  <p>How to export the result to CSV file? Specifically , the resulted id's ( _id: collection2_id ) should be exported to CSV file.</p>