DexCurl
DexCurl

Reputation: 1703

Rails Mongoid select where key/value pair in array

so I have a collection Groups that looks like this

[
    {
        \"_id\": \"51bdff3968c7c4dd30000003\",
        \"members\": [
            {
                \"id\": \"51bdedef68c7c4bc7c000001\",
                \"role\": \"admin\"
            },
            {
                \"id\": \"51be0d4568c7c473ef000007\",
                \"role\": \"user\"
            }
        ],
        \"name\": \"tetsing2\"
    },
    {
        \"_id\": \"51bdf97868c7c46604000002\",
        \"members\": [
            {
                \"id\": \"51be12ae68c7c4dcce000001\",
                \"role\": \"user\"
            },
            {
                \"id\": \"51be12db68c7c45e08000002\",
                \"role\": \"user\"
            }
        ],
        \"name\": \"ds\"
    }
]" 

I just what to get the object that in the members array has an id equal to 51be12db68c7c45e08000002

I can do it in the console mongo client with this command

db.groups.find({ "members.id": ObjectId("51be12db68c7c45e08000002") })

and it gives back just the one appropriate object named 'ds'

However with Mongoid in rails, when I try similar command like this:

@groups = Group.where(' { "members.id": "'+current_user.id+'"}')

I get back both objects.

I've looked through the docs, but does anyone know to how achieve this through Mongoid or can I run a console command through Monogoid or moped or something?

Thank you

Upvotes: 1

Views: 401

Answers (1)

cpuguy83
cpuguy83

Reputation: 5993

Group.where( :"members.id" => current_user.id )

Upvotes: 1

Related Questions