How can I find embedded Mongoid documents based on multiple criteria?

喜夏-厌秋 提交于 2019-12-07 12:14:43

问题


I have a Mongoid document with embedded documents in it. I want to search the top-level documents for all of them where there is an embedded document that has multiple criteria.

TopDoc.where('inside.first_name' => 'Bob', 'inside.last_name' => 'Jones')

But it seems to me this would match on a TopDoc with Bob Wever and Paul Jones, which is wrong.


回答1:


You need to use $elemMatch. With Mongoid, the following line should do the trick

TopDoc.elem_match(inside: { first_name: 'Bob', last_name: 'Jones' })

which is equivalent to :

TopDoc.where(:inside.elem_match => { first_name: 'Bob', last_name: 'Jones'})


来源:https://stackoverflow.com/questions/15034489/how-can-i-find-embedded-mongoid-documents-based-on-multiple-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!