Mongoid相交标准上嵌入文档

问题描述:

我试图让两个查询的交集上使用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) 

有没有更好的方法来构造这个查询?谢谢!

这里的问题是,由例如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'吗? –