How to stream MongoDB Query Results with nodejs?

前端 未结 5 727
名媛妹妹
名媛妹妹 2020-12-23 14:33

I have been searching for an example of how I can stream the result of a MongoDB query to a nodejs client. All solutions I have found so far seem to read the query result at

5条回答
  •  猫巷女王i
    2020-12-23 14:56

    node-mongodb-driver (the underlying layer that every mongoDB client uses in nodejs) except the cursor API that others mentioned has a nice stream API (#458). Unfortunately i did not find it documented elsewhere.

    Update: there are docs also here.

    It can be used like this:

    var stream = collection.find().stream()
    stream.on('error', function (err) {
      console.error(err)
    })
    stream.on('data', function (doc) {
      console.log(doc)
    })
    

    It actually implements the ReadableStream interface, so it has all the goodies (pause/resume etc)

提交回复
热议问题