sql >> Base de Datos >  >> NoSQL >> MongoDB

La mejor manera de consultar todos los documentos de una colección mongodb de forma reactiva sin inundar la RAM

No soy un experto en mongodb, pero según los ejemplos que he visto, este es un patrón que probaría.

He omitido los eventos que no sean datos, ya que limitar ese parece ser la principal preocupación.

var cursor = db.collection('mycollection').find({});  

const cursorNext = new Rx.BehaviourSubject('next');  // signal first batch then wait
const nextBatch = () => {
  if(cursor.hasNext()) {
    cursorNext.next('next');
  }
});

cursorNext
  .switchMap(() =>                            // wait for cursorNext to signal
     Rx.Observable.fromPromise(cursor.next())  // get a single doc
       .repeat()                               // get another
       .takeWhile(() => cursor.hasNext() )     // stop taking if out of data
       .take(batchSize)                        // until full batch
       .toArray()                              // combine into a single emit
  )
  .map(docsBatch => {
    // do something with the batch
    // return docsBatch or modified doscBatch
  })
  ... // other operators?
  .subscribe(x => {
    ...
    nextBatch();
  });         

Estoy tratando de armar una prueba de este flujo Rx sin mongodb, mientras tanto, esto podría darle algunas ideas.