1

I am fetching data from MongoDB as follows:

@bs = coll2.find("date" => {"$gte" => initial_date, "$lte" => Time.now.utc})

It works fine but when I render @bs, it sends empty.

  render :json => @bs

If I do a @bs.each and render each one as json, it works, however, I want to send the whole @bs.

Thanks

slugster
  • 49,403
  • 14
  • 95
  • 145
Donald
  • 243
  • 4
  • 10

1 Answers1

2

By default, #find returns a Mongo::Cursor object, not the actual results. You'll want to first convert the cursur (@bs) to an array with the results in it, and then render that as json.

render :json => @bs.to_a.to_json

Note that since it's a cursor, once you either return the results, or start iterating over them, then the to_a call will not return all the results. You'll need to call rewind! to reset the result set:

> @bs.to_a
# => [{"_id" => BSON::ObjectID.....]
> @bs.to_a
# => []
> @bs.rewind!
# => true
> @bs.to_a
# => [{"_id" => BSON::ObjectID.....]
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • Thanks, it makes sense. How do I conver the cursor to an array? Is there a simple way of doing it? – Donald May 11 '11 at 21:57
  • The `@bs.to_a` part of my example does that for you. Then you call `to_json` on the array to get JSON data. – Dylan Markow May 11 '11 at 22:02
  • I'm still getting [] but @bs is returning results. – Donald May 11 '11 at 22:07
  • Make sure you're not doing anything with `@bs` before the `to_a` call (i.e. the `to_a` call should be the first thing you do to `@bs` after running your `find` query). Since it's a cursor, doing something like `@bs.each...` will leave it pointing at the end of the result set. So when you then do `@bs.to_a` it returns an empty array. – Dylan Markow May 11 '11 at 22:20
  • Alternatively, you can call `@bs.rewind!` before the `to_a` to reset the result set. – Dylan Markow May 11 '11 at 22:21