简体   繁体   中英

How make a query with Mongodb with Ruby on Rails?

I have a object Post, with some attributes.And I want search there object by single attribute.In my example, it would be so

[58] pry(main)> Post.last
=> #<Post _id: 54e3852d776561352d020000, title: "123456", body: "4131231", draft: false, user_id: BSON::ObjectId('54e22da377656150d5000000')>

Need to find by 'draft' attribute.In postgres I would have done so

Post.where("draft = ?", false)

but how to do the same only Mongodb?

upd

[72] pry(main)> Post.where("draft = ?", false)
ArgumentError: wrong number of arguments (2 for 1)
from /home/weare138/.rvm/gems/ruby-2.1.5/bundler/gems/mongoid-660868d73b36/lib/mongoid/criteria.rb:416:in `where'

2upd

[2] pry(main)> Post.where(draft: false)
=> #<Mongoid::Criteria
  selector: {"draft"=>false}
  options:  {}
  class:    Post
  embedded: false>

You can use :

Post.where(draft: false).each { |rec| puts rec.title }
# or you can write
Post.where("this.draft == false").each do |rec|
  puts rec.title
end

Note: #where will give you Mongoid::Criteria object not the actual records. You have to iterate through this object using #each , #first to get the first record etc.

您可以在irb中尝试一下,看看标题是否显示:

Post.where(draft: false).map(&:title)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM