How to query a collection of embedded mongo documents to extract specific document with a list of criteria?

47 views
Skip to first unread message

Alexandre Ponsin

unread,
May 4, 2011, 8:53:35 AM5/4/11
to Mongoid
I am trying to select a collection of document based on the content of
their embedded documents.

My model looks like this:

class box
embeds_many :items
field :stuff
end

class item
field :attrib1
field :attrib2
field :array
end
So with this structure I can query with the following to extract a
collection of boxes bases on it's item's attributes:

Box.any_in(:'items.array' =>
[:value1, :value2]).where(:'items.attrib1'=> 'x', :'items.attrib2' =>
'y').order_by([:stuff, :asc])
So this query gives me a collection of box that contains items with
attributes 1 = x and attributes 2 = y and array that contains value1
or value2

This is all great, but the problem is that I need to tie up all the
attributes into 1 item. What I mean is that this query will return me
box like this:

box
{
items
[
{array => [value1], attrib1 => "x", attrib2 => "z"}
{array => [value1], attrib1 => "h", attrib2 => "y"}
]
}
The criteria's of the query are respected because it's true that
attrib1 = 'x' and attrib2 = 'y' in that box, but unfortunately not
within the same item.

That's what I need, the list of boxes contains items that have all the
desired values within the same item.

How can I do that ? I have just no idea ? I hope I made myself clear,
I wasn't really sure how to explain my problem

Thanks,

Alex

Rubish Gupta

unread,
May 4, 2011, 9:55:33 AM5/4/11
to mon...@googlegroups.com

Alexandre Ponsin

unread,
May 4, 2011, 1:44:57 PM5/4/11
to Mongoid
Nice ! that's exactly what I need, now how do I do that in mongoid ?

Alex

On May 4, 9:55 pm, Rubish Gupta <rubishgupt...@gmail.com> wrote:
> Take a look athttp://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Obj...
>
> <http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Obj...>I
> hope it should help.
>
> On Wed, May 4, 2011 at 6:23 PM, Alexandre Ponsin <alexandre.pon...@gmail.com

Rubish Gupta

unread,
May 4, 2011, 2:50:02 PM5/4/11
to mon...@googlegroups.com
I haven't tested this query as I have no documents matching the structure you are using(and I am too lazy to create one for testing), but this should give you the idea

Box.where(
  {
    "items" => {
      "$elemMatch" => {
        "array" => { "$in" => ["value1", "value2"]},
        "attrib1" => "x",
        "attrib2" => "y"
      }
    }
  }
)
Reply all
Reply to author
Forward
0 new messages