Mongoid - Queries

Posted vixennn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mongoid - Queries相关的知识,希望对你有一定的参考价值。

Queries

Find:

Actor.find("nm0993498").birth_name
#multiple id
Actor.find("nm000006", "nm0000008")

#
Movie.find_or_create_by()

#Does not persist, call save to persist
find_or_initialize_by()

 

where: 

Movie.where(:title => "Rocky")

Move.where(:year.gt => 2000).distinct(:title) 

# where ;$exists & :$regex 

writer = Writer.where(:hometown => {:exists => 0}).first

damon = Actor.where(:name => {:$regex => "Matt Da}).first

# where Geolocation query 
silver_spring = Place.where(:city=>"Silver Spring", :state=>"MD").first 

Actor.near(:"place_of_birth.geolocation=>silver_spring.geolocation").limit(5).each 

 

pluck and scope:

#pluck - give all the non nil value for the provided field

Movie.all.pluck(:title) 

#named scope

scope :current, -> {where(:year.gt => Date.current.year-2)}
Movie.current.where 

#default scope 
field :active, type: boolean, default: true 

#OR & in 

Movie.where(:year.gt => 2014).in(title:["The Martian"].pluck(:plot)

or conditional operator 
Movie.or({id: xxx},{title: "The Martian"}).pluck(:plot)

 

以上是关于Mongoid - Queries的主要内容,如果未能解决你的问题,请参考以下文章

Mongoid:如何防止批量赋值创建未定义的字段?

Mongoid:未初始化的常量(NameError)

Mongoid:嵌入文档在父级构造时自动初始化

gem 'mongoid', '~> 4' 是不是等于 gem 'mongoid', '>= 4'?

如何跳过 Mongoid 文档的回调?

mongoid 中的索引:我应该何时以及多久运行一次 rake db:mongoid:create_indexes?