Getting actual array of results using Mongoid
Asked Answered
D

2

19

With a regular ActiveRecord/SQL setup in Rails, in console when I execute commands *.where, *.all etc., I get back the actual array of record items. However, after switching to Mongoid, I instead get back a criteria. How do I get the actual results?

This is what I get now...

ruby-1.9.2-p180 :001 > App.all
 => #<Mongoid::Criteria
  selector: {},
  options:  {},
  class:    App,
  embedded: false>
Dhumma answered 7/7, 2011 at 6:56 Comment(0)
R
25

When you query a model in Mongoid, it returns a criteria object (as you've stated), it doesn't actually run the query until you request data from the criteria.

All you need to do is iterate over the results, using each or map or any of the array methods, like this:

App.all.each do |app|
  puts app.name
end

Alternatively, if you just want the array, you can just call to_a on the criteria:

App.all.to_a
Repro answered 7/7, 2011 at 8:17 Comment(0)
G
19

App.all.entries works as well.

Glissade answered 29/8, 2011 at 9:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.