3

If I have a few IDs, say [1,2,3]

Is it possible to query them all at once in Mongoid? Such as:

User.where({ id: [1,2,3]}) or something similar?

kidcapital
  • 5,064
  • 9
  • 46
  • 68

2 Answers2

11

The underlying MongoDB query you're looking for would use the $in operator:

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

In MongoDB, you'd say:

db.users.find({ id: { $in: [1,2,3] } })

That translates directly into Mongoid as:

User.where(id: { :$in => [1,2,3] })

Mongoid patches most (all?) of the query operators into Symbol so you'd usually say:

User.where(:id.in => [1,2,3])
mu is too short
  • 426,620
  • 70
  • 833
  • 800
6

Bit late to the party, but you can just pass an array of IDs to the find() method.

User.find(ids)
stefankolb
  • 328
  • 3
  • 16
  • 2
    `User.find(ids)` will return a plain Ruby array. If you want to do batch DB operations with the result, for example, it's better to use `User.where(:id.in => [1,2,3])`. – ph0rque Nov 21 '17 at 22:38