Mongoid - request for embedded documents

class Foo
  include Mongoid::Document
  field :name, type: String
  embeds_many :bars
end

class Bar
  include Mongoid::Document
  field :name, type: String
  embedded_in :foo
end

Is there any way that I can request everything barshere? In AR, I would do something like Bar.where(name: 'something')- just give me all the bars that match some criteria.

In a way, I can only request specific bars on a single foo. `Foo.first.bars.where (name: 'something'). I know that mongoDB has no unions, so ... I am wondering how to do this.

I am ready to completely lose Foo and do something like:

class Bar
  include Mongoid::Document
  field :foo_name, type: String
  field :name, type: String
end
+4
source share
1 answer

You cannot return an object Barwithout first returning the object Fooin which it is embedded.

(Foo) .

foo = Foo.create(:name => 'foo1')
foo.bars << Bar.new(:name => 'bar1')

Foo.where(:'bars.name' => 'bar1').first
=> #<Foo _id: 53c4a380626e6f813d000000, name: "foo1">

, Foos, , , , ( Array#find Array#select

foo.bars << Bar.new(:name => 'bar2')
Foo.where(:'bars.name' => 'bar1').first.bars.where(:name => 'bar2').first
=> #<Bar _id: 53c4a380626e6f813d000001, name: "bar2">

: , , . , : " , ". , . , /.

. 100M +, .

2: - , ,

+10

Source: https://habr.com/ru/post/1548428/


All Articles