[英]Mongodb: how to create a `tail -f` view on a capped collection?
我想在我的 Mongo 數據庫上的一個capped
集合(用作日志表)上創建一種“儀表板”。 這就是我創建集合的方式:
db.createCollection( "messages", { capped: true, size: 100000 } );
我做了一個collection.find()
,有選項tailable:true
、 awaitdata:true
和numberOfRetries:-1
(無限重試)。
讓我感到困惑的是,我希望 find().each() 循環等待新數據(消息)......相反(幾秒鍾后)它出錯了( No more documents in tailed cursor
...... :-()
這是我正在使用的代碼:
var mongo = require('mongodb');
mongo.MongoClient.connect('mongodb://127.0.0.1/myDb', function (err, db) {
db.collection('messages', function(err, collection) {
if (err) {
return console.error('error in status collection:', err);
}
collection.find( // open tailable cursor
{},
{ tailable: true, awaitdata: true, numberOfRetries: -1 }
).each(function(err, doc) {
if (err) {
if (err.message === 'No more documents in tailed cursor') {
console.log('finished!');
} else {
console.error('error in messages collection:', err);
}
} else {
if (doc) {
console.log('message:', doc.message);
}
}
})
});
});
我想念什么?
更新:
直到現在還沒有收到任何決定性的答案,我推斷MongoDb tailable collections
還沒有准備好迎接黃金時段...... :-(((
可悲的是放棄了更經典和更強大的 fs 日志記錄解決方案......
您可以使用 tailable find()
游標作為node.js 流來設置訂閱新 MongoDB 文檔的訂閱者函數。 下面證明了這一點:
// subscriber function
var subscribe = function(){
var args = [].slice.call(arguments);
var next = args.pop();
var filter = args.shift() || {};
if('function' !== typeof next) throw('Callback function not defined');
var mongo = require('mongodb');
mongo.MongoClient.connect('mongodb://127.0.0.1/myDb', function(err, db){
db.collection('messages', function(err, collection) {
var seekCursor = collection.find(filter).sort({$natural: -1}).limit(1);
seekCursor.nextObject(function(err, latest) {
if (latest) {
filter._id = { $gt: latest._id }
}
var cursorOptions = {
tailable: true,
awaitdata: true,
numberOfRetries: -1
};
var stream = collection.find(filter, cursorOptions).sort({$natural: -1}).stream();
stream.on('data', next);
});
});
});
};
// subscribe to new messages
subscribe( function(document) {
console.log(document);
});
也許有人也在尋找裸 mongo 終端解決方案(我的意思是,沒有現場收聽任何編程語言)。 如果您只想查看集合的結尾,請考慮使用此
db.oplog.rs.find().sort({$natural: -1})
希望我幫助過某人:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.