Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb: Search a collection for all IDs in an array of objects

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

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.

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.

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:

EDIT2 Nevermind my first edit. find() returns just a cursor, not the documents itself. So I used toArray(). Thanks for your help @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' }
like image 988
anstaendig Avatar asked Mar 17 '23 02:03

anstaendig


1 Answers

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:

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 });
like image 78
chridam Avatar answered Mar 18 '23 16:03

chridam