Search code examples
ruby-on-rails-3mongodbmongodb-ruby

Return JSON with data from MongoDB


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


Solution

  • 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.....]