简体   繁体   English

mongoose:查找所有具有特定字段的文档

[英]mongoose: find all the documents that have specific field

Some of my documents have an extra "Game" field like this我的一些文件有一个额外的"Game"字段,像这样

{
    "_id" : NumberLong(204648),
    "loc" : [ 
        -41.2887953, 
        174.7772114
    ],
    "ts" : "2020-09-11T02:54:11Z",
    "v" : 52,
    "game": 2, <-------- 
}

I want to return these documents that have any value in the "Game" field.我想返回这些在"Game"字段中具有任何值的文档。

mongoose.connection.db.collection('games').find({ "game": {} }, (err, docs) => {
        console.log(docs);
    });

I've tried with.我试过了。 However, it just returns undefined .但是,它只返回undefined How can I console.log just the documents that have a value of the "game" field?我怎样才能 console.log 只记录具有"game"字段值的文档?


const a = await mongoose.connection.db.collection('game').find({ game: { $exists: true } });
    console.log(a);

returns返回

Cursor {
  _readableState: ReadableState {
    objectMode: true,
    highWaterMark: 16,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: [],
    flowing: null,
    ended: false,
    endEmitted: false,
    reading: false,
    sync: true,
    needReadable: false,
    emittedReadable: false,
    readableListening: false,
    resumeScheduled: false,
    errorEmitted: false,
    emitClose: true,
    autoDestroy: true,
    destroyed: false,
    errored: null,
    closed: false,
    closeEmitted: false,
    defaultEncoding: 'utf8',
    awaitDrainWriters: null,
    multiAwaitDrain: false,
    readingMore: false,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: null
  },
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  operation: FindOperation {
    options: {
      skip: 0,
      limit: 0,
      raw: undefined,
      hint: null,
      timeout: undefined,
      slaveOk: true,
      readPreference: [ReadPreference],
      db: [Db],
      promiseLibrary: [Function: Promise]
    },
    ns: MongoDBNamespace { db: 'db', collection: 'game' },
    cmd: {
      find: 'db.game',
      limit: 0,
      skip: 0,
      query: [Object],
      raw: undefined,
      hint: null,
      timeout: undefined,
      slaveOk: true,
      readPreference: [ReadPreference]
    },
    readPreference: ReadPreference {
      mode: 'primary',
      tags: undefined,
      hedge: undefined
    },
    cursorState: {
      cursorId: null,
      cmd: [Object],
      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: 'db.game',
  namespace: MongoDBNamespace { db: 'db', collection: 'game' },
  cmd: {
    find: 'db.game',
    limit: 0,
    skip: 0,
    query: { tg: [Object] },
    raw: undefined,
    hint: null,
    timeout: undefined,
    slaveOk: true,
    readPreference: ReadPreference {
      mode: 'primary',
      tags: undefined,
      hedge: undefined
    }
  },
  options: {
    skip: 0,
    limit: 0,
    raw: undefined,
    hint: null,
    timeout: undefined,
    slaveOk: true,
    readPreference: ReadPreference {
      mode: 'primary',
      tags: undefined,
      hedge: undefined
    },
    db: Db {
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      s: [Object],
      serverConfig: [Getter],
      bufferMaxEntries: [Getter],
      databaseName: [Getter],
      [Symbol(kCapture)]: false
    },
    promiseLibrary: [Function: Promise]
  },
  topology: NativeTopology {
    _events: [Object: null prototype] {
      authenticated: [Function (anonymous)],
      error: [Array],
      timeout: [Array],
      close: [Array],
      parseError: [Array],
      fullsetup: [Array],
      all: [Array],
      reconnect: [Array],
      commandStarted: [Function (anonymous)],
      commandSucceeded: [Function (anonymous)],
      commandFailed: [Function (anonymous)],
      serverOpening: [Function (anonymous)],
      serverClosed: [Function (anonymous)],
      serverDescriptionChanged: [Function (anonymous)],
      serverHeartbeatStarted: [Function (anonymous)],
      serverHeartbeatSucceeded: [Array],
      serverHeartbeatFailed: [Function (anonymous)],
      topologyOpening: [Function (anonymous)],
      topologyClosed: [Function (anonymous)],
      topologyDescriptionChanged: [Function (anonymous)],
      joined: [Array],
      left: [Function (anonymous)],
      ping: [Function (anonymous)],
      ha: [Function (anonymous)],
      connectionPoolCreated: [Function (anonymous)],
      connectionPoolClosed: [Function (anonymous)],
      connectionCreated: [Function (anonymous)],
      connectionReady: [Function (anonymous)],
      connectionClosed: [Function (anonymous)],
      connectionCheckOutStarted: [Function (anonymous)],
      connectionCheckOutFailed: [Function (anonymous)],
      connectionCheckedOut: [Function (anonymous)],
      connectionCheckedIn: [Function (anonymous)],
      connectionPoolCleared: [Function (anonymous)],
      open: [Function],
      reconnectFailed: [Function (anonymous)]
    },
    _eventsCount: 36,
    _maxListeners: Infinity,
    s: {
      id: 0,
      options: [Object],
      seedlist: [Array],
      state: 'connected',
      description: [TopologyDescription],
      serverSelectionTimeoutMS: 30000,
      heartbeatFrequencyMS: 10000,
      minHeartbeatFrequencyMS: 500,
      Cursor: [class Cursor extends CoreCursor],
      bson: BSON {},
      servers: [Map],
      sessionPool: [ServerSessionPool],
      sessions: Set(0) {},
      promiseLibrary: [Function: Promise],
      credentials: undefined,
      clusterTime: null,
      connectionTimers: Set(0) {},
      sCapabilities: [ServerCapabilities]
    },
    [Symbol(kCapture)]: false,
    [Symbol(waitQueue)]: Denque {
      _head: 2,
      _tail: 2,
      _capacity: undefined,
      _capacityMask: 3,
      _list: [Array]
    }
  },
  cursorState: {
    cursorId: null,
    cmd: {
      find: 'db.game',
      limit: 0,
      skip: 0,
      query: [Object],
      raw: undefined,
      hint: null,
      timeout: undefined,
      slaveOk: true,
      readPreference: [ReadPreference]
    },
    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
}

I am not getting any document console.log but just this Cursor returns.我没有得到任何文件 console.log,但只有这个 Cursor 返回。

You can use $exists in this way:您可以通过这种方式使用$exists

db.collection.find({
  "game": {
    "$exists": true
  }
})

Example here这里的例子

Also, another options is compare to not equal null:此外,另一个选项是比较不等于 null:

db.collection.find({
  "game": {
    "$ne": null
  }
})

Example here这里的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM