我正在使用MubSub允许用户订阅某个查询,并在可用时立即获得推送的更新。此库使用有上限的集合来获取可跟踪游标。我遇到的问题是,当我只有一个可尾光标时,一切都很好。获取游标大约需要几毫秒。但是当我添加更多订阅(从而打开更多游标)时,游标的接收有时可能需要长达 8 秒的时间。我尝试添加索引,但这根本没有帮助。
以下是我收藏的统计数据:
{
"ns" : "mDB.myCollection",
"count" : 395669,
"size" : 325551880,
"avgObjSize" : 822.7884418541761,
"storageSize" : 1000001536,
"numExtents" : 1,
"nindexes" : 3,
"lastExtentSize" : 1000001536,
"paddingFactor" : 1,
"flags" : 1,
"totalIndexSize" : 81678240,
"indexSizes" : {
"subscriptionIndex" : 32704000,
"_id_" : 11593568,
"subscriptionQueryAsc" : 37380672
},
"capped" : 1,
"max" : 2147483647,
"ok" : 1
}
这是执行时间过长的代码段:
this.collection.then(handle(true, function(collection) {
var latest = null;
// The next statement takes a few ms for the first cursor,
// then 5+ seconds for more cursors
collection.find({}).sort({ $natural: -1 }).limit(1).nextObject(handle(function(doc) {
if (doc) latest = doc._id;
(function poll() {
if (latest) query._id = { $gt: latest };
var options = { tailable: true, awaitdata: true, numberOfRetries: -1 };
var cursor = collection.find(query, options).sort({ $natural: 1 });
(function more() {
cursor.nextObject(handle(function(doc) {
if (!doc) return setTimeout(poll, self.wait);
callback(doc);
latest = doc._id;
more();
}));
})();
})();
}));
}));
这是一个已知问题,还是我只是做错了什么?
我通过删除上面粘贴的代码中的以下行来解决此问题:
collection.find({}).sort({ $natural: -1 }).limit(1).nextObject(handle(function(doc) {
该特定语句使代码非常慢,可能是因为它正在获取所有({})文档,并且不知何故游标的数量减慢了该过程。我做了这样的事情:
this.collection.then(handle(true, function(collection) {
var latest = null;
if (doc) latest = doc._id;
(function poll() {
if (latest) query._id = { $gt: latest };
var options = { tailable: true, awaitdata: true, numberOfRetries: -1 };
var cursor = collection.find(query, options).sort({ $natural: 1 });
(function more() {
cursor.nextObject(handle(function(doc) {
if (!doc) return setTimeout(poll, self.wait);
callback(doc);
latest = doc._id;
more();
}));
})();
})();
}));
我不完全理解为什么MubSub的作者这样做,因为最后一个文档的_id是什么并不重要。这是因为文档插入到有上限的集合中,这会保留广告顺序。