Skip to content

Instantly share code, notes, and snippets.

@kinopyo
Created January 1, 2012 11:36
Show Gist options
  • Save kinopyo/1547098 to your computer and use it in GitHub Desktop.
Save kinopyo/1547098 to your computer and use it in GitHub Desktop.
MongoMapper query for not null column.

Goal

"Using MongoMapper to find all users that :name column is not null", this is all I want.

Solution

To do so, use this query:

User.where(:name.ne => nil).all
User.all(:name.ne => nil)

My mistakes:

User.where(:name.ne => nil)

See? If you don't contact with all explicitly, you fail. This is different from Rails ActiveRecord.

What is .ne?

ne means not equal. There are similar 'gt, lt, get, or' queries around.

You could get more information in http://www.mongodb.org/display/DOCS/Advanced+Queries

Other examples from mongo_mapper

/Users/username/.rvm/gems/ruby-1.9.2-p290/gems/mongo_mapper-0.10.1/examples/query.rb

User.all(:name => 'John')
User.all(:tags => %w[mongo])
User.all(:tags.all => %w[ruby mongo])
User.all(:age.gte => 30)

User.where(:age.gt => 27).sort(:age).all
User.where(:age.gt => 27).sort(:age.desc).all
User.where(:age.gt => 27).sort(:age).limit(1).all
User.where(:age.gt => 27).sort(:age).skip(1).limit(1).all
@wheelq
Copy link

wheelq commented Jul 19, 2014

strange. I have an array and when I use .nin it doesn't work. but it works with .ne check

@foglabs
Copy link

foglabs commented Feb 18, 2015

Nice, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment