2012-09-22 153 views
0

我試圖讓兩個查詢的交集上使用Mongoid 3.Mongoid相交標準上嵌入文檔

所以(例如假)想象我有一些嵌入式docuements:

class Post 
    embeds_many :comments 

    index 'comments.author_id' => 1 
end 

class Comments 
    embedded_in :post 
    belongs_to :author 
end 

如果我希望得到的職位從用戶評論我可能只是做

Post.where(:'comments.author_id' => User.first.id) 

但是,如果我想通過這兩個用戶有意見的帖子內容:

u1 = User.first.id 
u2 = User.last.id 
Post.where(:'comments.author_id' => u1.id, :'comments.author_id' => u2.id) 

這不mongoid 3.工作,它覆蓋了第一個comments.author_id與第二,所以你得到的東西是這樣的:

我沒有任何的運氣試圖
command={:count=>"posts", :query=>{"comments.author_id"=>"505d1eb5f8182b7082000017"}} 

其他變化:

Post.where(:'comments.author_id' => u1.id).where(:'comments.author_id' => u2.id) 
Post.where(:'comments.author_id' => u1.id).and.where(:'comments.author_id' => u2.id) 
Post.where(:'comments.author_id' => u1.id).intersect.where(:'comments.author_id' => u2.id) 
Post.all_of(:'comments.author_id' => u1.id, :'comments.author_id' => u2.id) 

有沒有更好的方法來構造這個查詢?謝謝!

回答

1

這裏的問題是,由例如Mongoid沒有得到一個機會來對它做任何事,因爲您提供之前地方執行方法它被評估爲只有1這關鍵的一個Ruby散列(由於密鑰是相同的):

Post.where(: 'comments.author_id'=> u1.id,: 'comments.author_id'=> u2.id)

你想要做的是什麼:

Post.any_in(: 'comments.author_id'=> [u1.id,u2.id])

+0

哦,是的,不能相信我沒有想想這個!感謝你的回答。相關問題:是否有可能從1位作者的評論中獲得評論,但是* *是否可以從其他評論中獲得評論?第二個有點像':'comments.author_id'.ne => u2.id'嗎? –