Rohit
Rohit

Reputation: 5721

Mongoid - Get all integer values

I have the following mongoid Model

class MyModel
  include Mongoid::Document
  field :myField
end

The value stored against myField can be of any datatype. I need to filter out, how many times an integer was stored against this field, or how many times a string was stored as the value.

Is there any way this can be done?

Please Help. Thanks in advance.

Upvotes: 0

Views: 166

Answers (1)

Arjan
Arjan

Reputation: 6274

Turns out there is a build-in mongo feature.

MyModel.where(:field.with_type => 2).count  # Number of strings
MyModel.where(:field.with_type => 16).count # Number of 32-bit integers

http://mongoid.org/en/origin/docs/selection.html

2 and 16 represent the BSON type for a string and a 32-bit integer.

For a complete list of BSON types and their corresponding numbers see:

http://docs.mongodb.org/manual/reference/operator/type/#op._S_type

Upvotes: 2

Related Questions