无法在mongodb副本集中执行$ lookup

问题描述 投票:0回答:1

我想从集合'posts'中获取帖子,并在集合'users'中存储用户的详细信息。帖子集合具有ID作为users集合的(_id)userId。我使用$ lookup从两个集合中检索数据。

const data = await db.collection('posts').aggregate([ { $lookup: { from: "users", localField: "ID", foreignField: "_id", as: "det"}}]);

在合并data时,它返回一个AggregationCursor对象,如下所示

AggregationCursor {


 _readableState: ReadableState {
    objectMode: true,
    highWaterMark: 16,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: null,
    pipesCount: 0,
    flowing: null,
    ended: false,
    endEmitted: false,
    reading: false,
    sync: true,
    needReadable: false,
    emittedReadable: false,
    readableListening: false,
    resumeScheduled: false,
    emitClose: true,
    autoDestroy: false,
    destroyed: false,
    defaultEncoding: 'utf8',
    awaitDrain: 0,
    readingMore: false,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: null
  },
  readable: true,
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  operation: AggregateOperation {
    options: { readPreference: [ReadPreference] },
    ns: MongoDBNamespace { db: 'alumni-portal', collection: '$cmd' },
    readPreference: ReadPreference { mode: 'primary', tags: undefined },
    readConcern: undefined,
    writeConcern: undefined,
    explain: false,
    fullResponse: true,
    target: 'posts',
    pipeline: [ [Object] ],
    hasWriteStage: false,
    cursorState: {
      cursorId: null,
      cmd: {},
      documents: [],
      cursorIndex: 0,
      dead: false,
      killed: false,
      init: false,
      notified: false,
      limit: 0,
      skip: 0,
      batchSize: 1000,
      currentLimit: 0,
      transforms: undefined,
      raw: undefined
    }
  },
  pool: null,
  server: null,
  disconnectHandler: undefined,
  bson: BSON {},
  ns: 'alumni-portal.$cmd',
  namespace: MongoDBNamespace { db: 'alumni-portal', collection: '$cmd' },
  cmd: {},
  options: {
    readPreference: ReadPreference { mode: 'primary', tags: undefined }
  },
  topology: NativeTopology {
    _events: [Object: null prototype] {
      authenticated: [Function],
      error: [Array],
      timeout: [Array],
      close: [Array],
      parseError: [Array],
      fullsetup: [Array],
      all: [Array],
      reconnect: [Array],
      commandStarted: [Function],
      commandSucceeded: [Function],
      commandFailed: [Function],
      serverOpening: [Function],
      serverClosed: [Function],
      serverDescriptionChanged: [Function],
      serverHeartbeatStarted: [Function],
      serverHeartbeatSucceeded: [Function],
      serverHeartbeatFailed: [Function],
      topologyOpening: [Function],
      topologyClosed: [Function],
      topologyDescriptionChanged: [Function],
      joined: [Function],
      left: [Function],
      ping: [Function],
      ha: [Function],
      connectionPoolCreated: [Function],
      connectionPoolClosed: [Function],
      connectionCreated: [Function],
      connectionReady: [Function],
      connectionClosed: [Function],
      connectionCheckOutStarted: [Function],
      connectionCheckOutFailed: [Function],
      connectionCheckedOut: [Function],
      connectionCheckedIn: [Function],
      connectionPoolCleared: [Function],
      open: [Function]
    },
    _eventsCount: 35,
    _maxListeners: Infinity,
    s: {
      id: 0,
      options: [Object],
      seedlist: [Array],
      state: 'connected',
      description: [TopologyDescription],
      serverSelectionTimeoutMS: 30000,
      heartbeatFrequencyMS: 10000,
      minHeartbeatFrequencyMS: 500,
      Cursor: [Function: Cursor],
      bson: BSON {},
      servers: [Map],
      sessionPool: [ServerSessionPool],
      sessions: Set {},
      promiseLibrary: [Function: Promise],
      credentials: [MongoCredentials],
      clusterTime: [Object],
      connectionTimers: Set {},
      sCapabilities: [ServerCapabilities]
    },
    [Symbol(kCapture)]: false,
    [Symbol(waitQueue)]: Denque { _head: 3, _tail: 3, _capacityMask: 3, _list: [Array] }
  },
  cursorState: {
    cursorId: null,
    cmd: {},
    documents: [],
    cursorIndex: 0,
    dead: false,
    killed: false,
    init: false,
    notified: false,
    limit: 0,
    skip: 0,
    batchSize: 1000,
    currentLimit: 0,
    transforms: undefined,
    raw: undefined
  },
  logger: Logger { className: 'Cursor' },
  s: {
    numberOfRetries: 5,
    tailableRetryInterval: 500,
    currentNumberOfRetries: 5,
    state: 0,
    promiseLibrary: [Function: Promise],
    explicitlyIgnoreSession: false
  },
  [Symbol(kCapture)]: false
}

但是相同的代码在mongoshell中返回所需的输出。我不明白为什么data返回一个AggregationCursor对象。预先谢谢你。

PS-我正在使用3个节点的副本集。

mongodb mongodb-query aggregation-framework replicaset mongo-shell
1个回答
0
投票

我只需要在代码语句的末尾添加。toArray()。因此,以上代码声明的答案应如下所示。

const data = await db.collection('posts').aggregate([ { $lookup: { from: "users", localField: "ID", foreignField: "_id", as: "det"}}]).toArray();
© www.soinside.com 2019 - 2024. All rights reserved.