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。我怎么能这样做?
答案 0 :(得分:0)
在下面的测试中,方法addresses_without_an_order通过Rails / Mongoid回答您的问题。 它既简单又直接,但效率低下,这对您来说可能不重要。 为了进一步启发,我们假设你想要更高效的东西。 通过Order集合上的外键引用address_id实现1对1关系。 因此,对Address集合的简单查询无法回答您的问题。 MongoDB不会在两个集合之间实现连接(放弃连接以支持分片)。
要在MongoDB中以更高的效率获得等效的连接,请将子项嵌入父项中。 address_without_a_contact方法显示了使用嵌入来回答问题的难易程度。 对于1对1的关系,嵌入很容易且明显,并且具有比加入更高的性能。 希望这能回答你的问题。
应用程序/模型/ address.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
$ rake test
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