首页 > 解决方案 > MongoDB 聚合失败并出现 afterClusterTime 错误

问题描述

我正在运行一个 MongoDB 4.0 复制集并从 NodeJs 访问它,但在使用聚合时遇到了问题。

当聚合返回的结果数超过默认或指定的 batchSize 时,我收到以下错误:

MongoError: afterClusterTime is not allowed for this command
at ...\mongodb-core\lib\connection\pool.js:581:63
at authenticateStragglers (...\mongodb-core\lib\connection\pool.js:504:16)
at Connection.messageHandler (...\mongodb-core\lib\connection\pool.js:540:5)
at emitMessageHandler (...\mongodb-core\lib\connection\connection.js:310:10)
at Socket.<anonymous> (...\mongodb-core\lib\connection\connection.js:453:17)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:559:20)

我已将问题缩小到会话的使用,这是 MongoDB 或 NodeJS 驱动程序的问题,还是我在如何执行此操作时遗漏了什么。

作为参考,以下足以说明问题。

使用零配置 MongoDB运行器 (run-rs --version=4.0.0)生成的 MongoDB 4.0 复制集

节点

包.json

 {
  "name": "aggregate_test",
  "dependencies": {
    "mongodb": "^3.1.4",
    "yargs": "^12.0.5"
  }
}

index.js

#!/usr/bin/env node
var args = require('yargs').argv;
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017,localhost:27018,localhost:27019?replicaSet=rs', {useNewUrlParser: true})
    .then(function (client) {
        var session = args.session !== false ? client.startSession() : undefined;
        var db = client.db('test');
        var collection = db.collection('test_collection');
        return collection.insertMany([
                    {item: 'one'},
                    {item: 'two'},
                    {item: 'three'}
                ], {session: session})
            .then(function () {
                return collection.aggregate(
                    [{$match: {item: {$exists: true}}}],
                    {session: session, cursor: {batchSize: 1}});
            })
            .then(function (cursor) {
                /* Error occurs as result of this call */
                return cursor.toArray();
            });
    })
    .then(function (result) {
        console.log(result);
        process.exit(0);
    })
    .catch(function (err) {
        console.error(err);
        process.exit(1);
    });

标签: node.jsmongodbaggregation-framework

解决方案


推荐阅读