2012-05-22 35 views
0

我有一個Mongo集合,它只是將一個ID引用到另一個集合。假設我特別提到的這個集合可能被稱爲:Mongoid查詢引用一個ID但不使用嵌入式文檔

步行。漫步有一個對owner_id的引用。業主每天都要帶着許多寵物散步。我想要做的是查詢步行列表,其中包含N個owner_id列表,並且只獲取他們對owner_id所擁有的每個所有者和組的最後一步。要根據上述清單獲得所有的散步清單,我們會做類似的事情。

Walk.any_in(:owner_id => list_of_ids)

我的問題是,有沒有辦法來查詢LIST_OF_IDS,得到每owner_id只有一個步行(最後一個,他們拿了可以通過現場created_at進行排序,並在哈希回來,在那裏每走被指向一個owner_id如:

{ 5 => {..walk data..}, 10 => {.. walk data ..}}

回答

0

下面是一個使用MongoDB的group命令 出於測試的目的,答案,我用walk_time我而不是created_at。 希望這有助於你喜歡它。

class Owner 
    include Mongoid::Document 
    field :name, type: String 
    has_many :walks 
end 

class Walk 
    include Mongoid::Document 
    field :pet_name, type: String 
    field :walk_time, type: Time 
    belongs_to :owner 
end 

測試/單元/ walk_test.rb

require 'test_helper' 

class WalkTest < ActiveSupport::TestCase 
    def setup 
    Owner.delete_all 
    Walk.delete_all 
    end 

    test "group in Ruby" do 
    walks_input = { 
     'George' => [ ['Fido', 2.days.ago], ['Fifi', 1.day.ago], ['Fozzy', 3.days.ago] ], 
     'Helen' => [ ['Gerty', 4.days.ago], ['Gilly', 2.days.ago], ['Garfield', 3.days.ago] ], 
     'Ivan' => [ ['Happy', 2.days.ago], ['Harry', 6.days.ago], ['Hipster', 4.days.ago] ] 
    } 
    owners = walks_input.map do |owner_name, pet_walks| 
     owner = Owner.create(name: owner_name) 
     pet_walks.each do |pet_name, time| 
     owner.walks << Walk.create(pet_name: pet_name, walk_time: time) 
     end 
     owner 
    end 
    assert_equal(3, Owner.count) 
    assert_equal(9, Walk.count) 
    condition = { owner_id: { '$in' => owners[0..1].map(&:id) } } # don't use all owners for testing 
    reduce = <<-EOS 
     function(doc, out) { 
     if (out.last_walk == undefined || out.last_walk.walk_time < doc.walk_time) 
      out.last_walk = doc; 
     } 
    EOS 
    last_walk_via_group = Walk.collection.group(key: :owner_id, cond: condition, initial: {}, reduce: reduce) 
    p last_walk_via_group.collect{|r|[Owner.find(r['owner_id']).name, r['last_walk']['pet_name']]} 
    last_walk = last_walk_via_group.collect{|r|Walk.new(r['last_walk'])} 
    p last_walk 
    end 
end 

測試輸出

Run options: --name=test_group_in_Ruby 

# Running tests: 

[["George", "Fifi"], ["Helen", "Gilly"]] 
[#<Walk _id: 4fbfa7a97f11ba53b3000003, _type: nil, pet_name: "Fifi", walk_time: 2012-05-24 15:39:21 UTC, owner_id: BSON::ObjectId('4fbfa7a97f11ba53b3000001')>, #<Walk _id: 4fbfa7a97f11ba53b3000007, _type: nil, pet_name: "Gilly", walk_time: 2012-05-23 15:39:21 UTC, owner_id: BSON::ObjectId('4fbfa7a97f11ba53b3000005')>] 
. 

Finished tests in 0.051868s, 19.2797 tests/s, 38.5594 assertions/s. 

1 tests, 2 assertions, 0 failures, 0 errors, 0 skips