mongodb:搜索对象数组中的所有id

时间:2021-12-14 21:18:12

I have an array of objects with only ObjectIDs and want to search a collection for all the documents with those IDs.

我有一个对象数组,只使用ObjectIDs,并希望用这些id搜索所有文档的集合。

var array = [{ _id: 5551e59be360594cd3319644 },
             { _id: 5551e59be360594cd3319631 },
             { _id: 5551e59be360594cd33195d2 },
             { _id: 5551e59be360594cd3319627 }];

Here is what I'm currently doing to get my result:

以下是我目前正在做的,以得到我的结果:

for (var i = 0; i < array.length; i++) {
  db.collection('test').findOne({_id:array[i]._id}, function(err, matched) {
    console.log(matched);
});

I tried to work with the $inoperator but had no success because it's not an array of IDs but an array of objects with those IDs inside.

我尝试使用$inoperator,但没有成功,因为它不是一个IDs数组,而是一个包含了这些id的对象数组。

Is there another way to do this with just one database query as I don't think it's a great idea to do so many database queries in a for loop.

是否有另一种方法可以只使用一个数据库查询,因为我认为在for循环中执行这么多数据库查询不是一个好主意。

EDIT I now tried it with the map method (like @chrisdam explained) so I have an array of the IDs but when i pass it to the find method i get this result:

我现在尝试使用map方法(如@chrisdam解释),所以我有一个id数组,但是当我将它传递给find方法时,我得到了这个结果:

EDIT2 Nevermind my first edit. find() returns just a cursor, not the documents itself. So I used toArray(). Thanks for your help @chrisdam!!

EDIT2不在乎我的第一次编辑。find()只返回一个游标,而不是文档本身。所以我使用toArray()。谢谢你的帮助@chrisdam!

{ db:
  { domain: null,
    _events: {},
    _maxListeners: undefined,
    databaseName: 'test',
    serverConfig: { 
      domain: null,
      _events: {},
      _maxListeners: undefined,
      auth: [Getter],
      _callBackStore: [Object],
      _commandsStore: [Object],
      _dbStore: [Object],
      host: 'localhost',
      port: 27017,
      options: [Object],
      internalMaster: true,
      connected: true,
      poolSize: 5,
      disableDriverBSONSizeCheck: false,
      _used: true,
      replicasetInstance: null,
      emitOpen: false,
      ssl: false,
      sslValidate: false,
      sslCA: null,
      sslCert: undefined,
      sslKey: undefined,
      sslPass: undefined,
      serverCapabilities: [Object],
      name: 'localhost:27017',
      socketOptions: [Object],
      logger: [Object],
      eventHandlers: [Object],
      _serverState: 'connected',
      _state: [Object],
      recordQueryStats: false,
      socketTimeoutMS: [Getter/Setter],
      _readPreference: [Object],
      db: [Circular],
      dbInstances: [Object],
      connectionPool: [Object],
      isMasterDoc: [Object] },
    options: { 
      read_preference_tags: null,
      read_preference: 'primary',
      url: 'mongodb://localhost:27017/test',
      native_parser: true,
      readPreference: [Object],
      safe: false,
      w: 1 },
    _applicationClosed: false,
    slaveOk: false,
    bufferMaxEntries: -1,
    native_parser: true,
    bsonLib: { 
      BSON: [Object],
      Long: [Object],
      ObjectID: [Object],
      DBRef: [Object],
      Code: [Object],
      Timestamp: [Object],
      Binary: [Object],
      Double: [Object],
      MaxKey: [Object],
      MinKey: [Object],
      Symbol: [Object] },
    bson: { promoteLongs: true },
    bson_deserializer: { 
      Code: [Object],
      Symbol: [Object],
      BSON: [Object],
      DBRef: [Object],
      Binary: [Object],
      ObjectID: [Object],
      Long: [Object],
      Timestamp: [Object],
      Double: [Object],
      MinKey: [Object],
      MaxKey: [Object],
      promoteLongs: true },
    bson_serializer: { 
      Code: [Object],
      Symbol: [Object],
      BSON: [Object],
      DBRef: [Object],
      Binary: [Object],
      ObjectID: [Object],
      Long: [Object],
      Timestamp: [Object],
      Double: [Object],
      MinKey: [Object],
      MaxKey: [Object],
      promoteLongs: true },
    _state: 'connected',
    pkFactory: { 
      [Function: ObjectID]
      index: 13651524,
      createPk: [Function: createPk],
      createFromTime: [Function: createFromTime],
      createFromHexString: [Function: createFromHexString],
      isValid: [Function: isValid],
      ObjectID: [Circular],
      ObjectId: [Circular] },
    forceServerObjectId: false,
    safe: false,
    notReplied: {},
    isInitializing: true,
    openCalled: true,
    commands: [],
    logger: { error: [Function], log: [Function], debug: [Function] },
    tag: 1431517732801,
    eventHandlers: { 
      error: [],
      parseError: [],
      poolReady: [],
      message: [],
      close: [] },
    serializeFunctions: false,
    raw: false,
    recordQueryStats: false,
    retryMiliSeconds: 1000,
    numberOfRetries: 60,
    readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined } },
  collection: { 
    db: { 
      domain: null,
      _events: {},
      _maxListeners: undefined,
      databaseName: 'test',
      serverConfig: [Object],
      options: [Object],
      _applicationClosed: false,
      slaveOk: false,
      bufferMaxEntries: -1,
      native_parser: true,
      bsonLib: [Object],
      bson: [Object],
      bson_deserializer: [Object],
      bson_serializer: [Object],
      _state: 'connected',
      pkFactory: [Object],
      forceServerObjectId: false,
      safe: false,
      notReplied: {},
      isInitializing: true,
      openCalled: true,
      commands: [],
      logger: [Object],
      tag: 1431517732801,
      eventHandlers: [Object],
      serializeFunctions: false,
      raw: false,
      recordQueryStats: false,
      retryMiliSeconds: 1000,
      numberOfRetries: 60,
      readPreference: [Object] },
    collectionName: 'sick',
    internalHint: null,
    opts: {},
    slaveOk: false,
    serializeFunctions: false,
    raw: false,
    readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
    pkFactory: { 
      [Function: ObjectID]
      index: 13651524,
      createPk: [Function: createPk],
      createFromTime: [Function: createFromTime],
      createFromHexString: [Function: createFromHexString],
      isValid: [Function: isValid],
      ObjectID: [Circular],
      ObjectId: [Circular] },
    serverCapabilities: undefined },
  selector: { _id: { '$in': [Object] } },
  fields: undefined,
  skipValue: 0,
  limitValue: 0,
  sortValue: undefined,
  hint: null,
  explainValue: undefined,
  snapshot: undefined,
  timeout: true,
  tailable: undefined,
  awaitdata: undefined,
  oplogReplay: undefined,
  numberOfRetries: 5,
  currentNumberOfRetries: 5,
  batchSizeValue: 0,
  raw: false,
  readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
  returnKey: undefined,
  maxScan: undefined,
  min: undefined,
  max: undefined,
  showDiskLoc: undefined,
  comment: undefined,
  tailableRetryInterval: 100,
  exhaust: false,
  partial: false,
  slaveOk: false,
  maxTimeMSValue: undefined,
  connection: undefined,
  transforms: undefined,
  totalNumberOfRecords: 0,
  items: [],
  cursorId: { _bsontype: 'Long', low_: 0, high_: 0 },
  dbName: undefined,
  state: 0,
  queryRun: false,
  getMoreTimer: false,
  collectionName: 'test.sick' }

1 个解决方案

#1


4  

You could try the JavaScript's native map method to generate an ObjectIds array that you can then use with the $in operator as follows:

您可以尝试使用JavaScript的本机映射方法生成一个objective - array,然后使用$in操作符,如下所示:

var array = [{ _id: "5551e59be360594cd3319644" },
             { _id: "5551e59be360594cd3319631" },
             { _id: "5551e59be360594cd33195d2" },
             { _id: "5551e59be360594cd3319627" }],    
    ids = array.map(function (obj){ return ObjectId(obj._id)});

db.collection.find({ "_id": { "$in": ids }});

OR just use the $or operator as:

或者使用$或操作符:

var array = [{ _id: "5551e59be360594cd3319644" },
             { _id: "5551e59be360594cd3319631" },
             { _id: "5551e59be360594cd33195d2" },
             { _id: "5551e59be360594cd3319627" }],    
    ids = array.map(function (obj){ return { _id: ObjectId(obj._id) } });   

db.collection.find({ "$or": ids });

#1


4  

You could try the JavaScript's native map method to generate an ObjectIds array that you can then use with the $in operator as follows:

您可以尝试使用JavaScript的本机映射方法生成一个objective - array,然后使用$in操作符,如下所示:

var array = [{ _id: "5551e59be360594cd3319644" },
             { _id: "5551e59be360594cd3319631" },
             { _id: "5551e59be360594cd33195d2" },
             { _id: "5551e59be360594cd3319627" }],    
    ids = array.map(function (obj){ return ObjectId(obj._id)});

db.collection.find({ "_id": { "$in": ids }});

OR just use the $or operator as:

或者使用$或操作符:

var array = [{ _id: "5551e59be360594cd3319644" },
             { _id: "5551e59be360594cd3319631" },
             { _id: "5551e59be360594cd33195d2" },
             { _id: "5551e59be360594cd3319627" }],    
    ids = array.map(function (obj){ return { _id: ObjectId(obj._id) } });   

db.collection.find({ "$or": ids });