0
class Address
    has_one :order
end

class Order
    index({address_id: 1, background: true})
    belongs_to :address
end

一个订单总是有一个address_id,但一个地址可以存在而不被一个订单关联。我正在尝试查找没有订单的所有地址,例如 order.address_id == address.id。我怎样才能做到这一点?

4

1 回答 1

0

在下面的测试中,addresses_without_an_order 方法通过 Rails/Mongoid 回答了您的问题。它简单明了,但效率低下,这对您来说可能重要也可能不重要。为了进一步启发,我们假设您想要更高效的东西。一对一关系是通过 Order 集合上的外键引用 address_id 实现的。因此,对地址集合的简单查询无法回答您的问题。MongoDB 不实现两个集合之间的连接(放弃连接以支持分片)。

为了在 MongoDB 中以更高的效率获得相当于 join 的效果,请将 child 嵌入到 parent。方法addresses_without_a_contact 显示了使用嵌入来回答您的问题是多么容易。对于 1 对 1 的关系,嵌入是简单而明显的,并且比连接具有显着更高的性能。希望这能回答你的问题。

应用程序/模型/地址.rb

class Address
  include Mongoid::Document
  has_one :order
  embeds_one :contact
end

应用程序/模型/order.rb

class Order
  include Mongoid::Document
  index({address_id: 1}, {background: true})
  belongs_to :address
end

应用程序/模型/contact.rb

class Contact
  include Mongoid::Document
  embedded_in :address
end

测试/单元/address_test.rb

require 'test_helper'

class AddressTest < ActiveSupport::TestCase
  def setup
    Address.delete_all
    Order.delete_all
    puts
  end
  test "0. mongoid version" do
    puts "Mongoid::VERSION:#{Mongoid::VERSION}\nMoped::VERSION:#{Moped::VERSION}"
  end
  def addresses_without_an_order
    Address.all.collect{|address| address.order == nil ? address : nil}.compact
  end
  def addresses_without_a_contact
    Address.where(:contact.exists => false).to_a
  end
  test "Address" do
    address = Address.create(street: "229 W 43rd Street, 5th FL", city: "New York", state: "NY", zip: "10036")
    assert_equal 1, Address.count
    puts "addresses_without_an_order: #{addresses_without_an_order.inspect}"
    puts "addresses_without_a_contact: #{addresses_without_a_contact.inspect}"
    address.order = Order.create(ASIN: "B00DUW4BMS", title: "The C++ Programming Language (4th Edition)", author: "Bjarne Stroustrup")
    address.contact = Contact.new(name: "Isabel")
    assert_equal 1, Order.count
    assert_equal [], addresses_without_an_order
    assert_equal [], addresses_without_a_contact
  end
end

$耙子测试

Run options:

# Running tests:

[1/2] AddressTest#test_0._mongoid_version
Mongoid::VERSION:3.1.5
Moped::VERSION:1.5.1
[2/2] AddressTest#test_Address
addresses_without_an_order: [#<Address _id: 528a5fa37f11ba7227000001, street: "229 W 43rd Street, 5th FL", city: "New York", state: "NY", zip: "10036">]
addresses_without_a_contact: [#<Address _id: 528a5fa37f11ba7227000001, street: "229 W 43rd Street, 5th FL", city: "New York", state: "NY", zip: "10036">]
Finished tests in 0.054955s, 36.3934 tests/s, 72.7868 assertions/s.
2 tests, 4 assertions, 0 failures, 0 errors, 0 skips
于 2013-11-18T19:05:59.220 回答