如何在rails app中使用mongoid在mongodb中的集合(多级查询/连接)中查找引用文档?

时间:2013-10-17 21:30:30

标签: sql mongodb mongoid document nosql

所有关于has_and_belongs_to_many关系和mongodb中的查询都在rails应用程序中使用mongid3

我有class Aclass B,说:

class A
  include Mongoid::Document
  has_and_belongs_to_many :bs
end

class B
  include Mongoid::Document
  has_and_belongs_to_many :as
end

现在实例化3 a - s和3 b - s:

a1 = A.create()
a2 = A.create()
a3 = A.create()

b1 = B.create()
b2 = B.create()
b3 = B.create()

现在彼此引用它们,例如:

a1.bs.push([b1, b3])
a2.bs.push([b2, b3])
a3.bs.push(b2)

所以:

b1.as.all
 => [<#A _id: 1000000000000001>] # i.e. a1

b2.as.all
 => [<#A _id: 1000000000000002>, <#A _id: 1000000000000003>] # i.e. a2, a3

b3.as.all
 => [<#A _id: 1000000000000001>, <#A _id: 1000000000000002>] # i.e. a1, a2

类似于a - s:

a1.bs.all
 => [<#B _id: 2000000000000001>, <#B _id: 2000000000000003>] # i.e. b1, b3

a2.bs.all
 => [<#B _id: 2000000000000002>, <#B _id: 2000000000000003>] # i.e. b2, b3

a3.bs.all
 => [<#B _id: 2000000000000002>] # i.e. b2

现在我想要那些a - 具有b - s的

  • A3:

    • a1具有b1,b3,其具有:[[a1],[a1,a2]] =&gt; [a1,a2] =&gt;不包括a1
    • a2具有b2,b3,其具有:[[a2,a3],[a1,a2]] =&gt; [a1,a2,a3] =&gt;包括a2
    • a3具有b2,其具有[[a2,a3]] =&gt; [a2,a3] =&gt;包括a3

      =&GT; [a2,a3] =&gt; [&lt; #A _id:1000000000000002&gt;,&lt; #A _id:1000000000000003&gt;]

  • a1和a2:

    • a1具有b1,b3,其具有:[[a1],[a1,a2]] =&gt; [a1,a2] =&gt;包括a1
    • a2具有b2,b3,其具有:[[a2,a3],[a1,a2]] =&gt; [a1,a2,a3] =&gt;包括a2
    • a3具有b2,其具有[[a2,a3]] =&gt; [a2,a3] =&gt;不包括a3

      =&GT; [a1,a2] =&gt; [&lt; #A _id:1000000000000001&gt;,&lt; #A _id:1000000000000002&gt;]

  • 不包含a1

    • a1具有b1,b3,其具有:[[a1],[a1,a2]] =&gt; [a1,a2] =&gt;包括a1
    • a2具有b2,b3,其具有:[[a2,a3],[a1,a2]] =&gt; [a1,a2,a3] =&gt;包括a2
    • a3具有b2,其具有[[a2,a3]] =&gt; [a2,a3] =&gt;不包括a3

      =&GT; [a3] =&gt; [&lt; #A _id:1000000000000003&gt;]

我觉得这很容易:

 A.all.where("b.id" => a1._id).count
  => 0

 A.all.where(:"bs.id" => a1._id).count
  => 0

 A.all.where(:"b.id" => "1000000000000003").count
  => 0

但是没有......

TLDP:如何查找包含所需文档的集合的文档? (比如多级查询)?

1 个答案:

答案 0 :(得分:1)

查找HasMany(或HABTM)关系是否与另一方(belongs_to或HABTM)有关系的查询是:

A.in(b_ids: [b1.id])
# return criteria for : All A's that b_ids has b1.id

它也是这样的:

A.where(:b_ids.in => [b1.id])

如果要查询多个数组项,必须使用mongodb $all运算符:

A.where(:b_ids.all [b1.id,b2.id])
# return criteria for : All A's that b_ids has b1.id and b2.id

Mongoid/Origin.Selection Documentation

MongoDB $in operator

MongoDB $all operator