AppTest
AppTest

Reputation: 501

Find documents with array of string ID's in MongoDB

I have an string array of id's that i'd like to use with the find function.

db.companies.find( { _id : { $in : arr} });

arr looks something like this,

[ '563a2c60b511b7ff2c61e938', '563a2c60b511b7ff2c61e8b7' ];

I see from the documentation that ObjectID() doesn't accept arrays. How can I search for a list of documents with this array? Will I have to recreate the array so that all elements are ObjectID's?

Upvotes: 2

Views: 3486

Answers (1)

dreyescat
dreyescat

Reputation: 13798

One option is to use the map function to get the list of ObjectId's from the list of string ids:

arr.map(function (id) {
  return ObjectId(id);
})

Plugged into your query:

db.companies.find({_id: { $in: arr.map(function (id) {return ObjectId(id);})}})

Upvotes: 7

Related Questions