1

I have an array of values, such as:

let items = ["abcd", "efgh", "ijkl", "mnop"]

Sometimes there are a thousand items in this array, other times there are only a few. I also have a series of documents with a schema including:

mongoose.Schema({
    name: { required: true, type: String }
})

Is there a faster way of querying for these items other than:

Model.find({ $or: [ items.map(item => ({ 'name': item })) ] }
Alexander Craggs
  • 7,874
  • 4
  • 24
  • 46
  • Possible duplicate of [Mongodb : $in operator vs lot of single queries](https://stackoverflow.com/questions/8219409/mongodb-in-operator-vs-lot-of-single-queries) and https://stackoverflow.com/questions/8145523/mongodb-find-by-multiple-array-items – Ashh Sep 27 '18 at 17:04
  • 1
    Oh hey, so it is. I had my mind totally fixated on `$in` being querying for a single values when the schema is an array of values. Thanks! – Alexander Craggs Sep 27 '18 at 17:10

1 Answers1

2

Sure, that's what the $in operator is for:

Model.find({name: {$in: items}})

The $in operator selects the documents where the value of a field equals any value in the specified array.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • 1
    Being top user with mongodb you should have marked it as duplicate – Dark Knight Sep 27 '18 at 17:17
  • @DarkKnight I think it's actually a different enough question from the marked dupe as this involves $or vs multiple queries. Anyway, that was my reasoning. – JohnnyHK Sep 27 '18 at 17:23