我有一個用戶數據庫mongodb,我想通過JSON的REST接口導出。問題是,在最壞的情況下,返回的行數已經超過200萬。如何使用node.js http服務器從mongodb返回大量行?
首先我想這
var mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db;
var server = new Server('localhost', 27017, {auto_reconnect: true});
var db = new Db('tracking', server);
var http = require('http');
http.createServer(function (request, response) {
db.collection('users', function(err, collection) {
collection.find({}, function(err, cursor){
cursor.toArray(function(err, items) {
output = '{"users" : ' + JSON.stringify(items) + '}';
response.setHeader("Content-Type", "application/json");
response.end(output);
});
});
});
}).listen(8008);
console.log('Server running at localhost:8008');
運行內存時失敗。該示例使用node-mongodb-native驅動程序和基本的http軟件包。
FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory
(注意,我用的需要,限制的結果參數真實的情景,但這個例子查詢所有這些這是最壞的情況下,無論)
數據本身很簡單,就像
{ "_id" : ObjectId("4f993d1c5656d3320851aadb"), "userid" : "80ec39f7-37e2-4b13-b442-6bea57472537", "user-agent" : "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322)", "ip" : "127.0.0.1", "lastupdate" : 1335442716 }
我也嘗試過類似
while(cursor != null)
{
cursor.nextObject(function(err, item) {
response.write(JSON.stringify(item));
});
}
但跑出來的記憶也。
我該如何繼續?應該有一種方法可以逐行地對數據進行流式處理,但是我一直無法找到合適的示例。由於外部應用程序需求,分頁數據不存在問題。我想將數據寫入一個文件然後發佈,但這會導致不需要的io。
我發現'cursor.stream()'和'cursor.each()'完全一樣。 – Meekohi
確保爲數千行或數百萬行指定'batchSize'的值 – alexishacks
您可以在此處粘貼您的完整代碼 – parkerproject