Search code examples
rubymongodbmongodb-ruby

Finding the size of a Mongo::Collection::View


I am trying to find the size of the result of a query in MongoDB and ruby:

size = collection.find({ foo: 'bar' }).size
if size > 0
  print "There are #{size} results!"
else
  print "There aren't any results."
end

However, when I run this, I get the following error:

undefined method `size' for #<Mongo::Collection::View:0x00000004141d48>

How do I determine the number of items returned by this query properly? I couldn't find any information in the documentation.


Solution

  • collection.find({ foo: 'bar' }).count()
    

    should solve your problem. There is no size method available in mongo but there is count.