Querying the MongoDB by id of a subdocument

1,882 views
Skip to first unread message

course_

unread,
May 23, 2012, 1:50:25 PM5/23/12
to mongodb-user
Is there a way to query by id of a subdocument ?

I have document model like this ..

[favouriteSubscribers] => Array
(
[0] => Array
(
[$ref] => Subscriber
[$id] => 4f510c663a4b0b0405000048
[$db] => prod
)

[1] => Array
(
[$ref] => Subscriber
[$id] => 4f185a523a4b0bd92a000001
[$db] =>prod
)
///

And I want to query by id

this does not seem to work ..

{"favouriteSubscribers.id":{"$regex":"4f8b593c3a4b0b045e000039"}}

is there a correct way of querying ?

A

A. Jesse Jiryu Davis

unread,
May 23, 2012, 2:53:11 PM5/23/12
to mongod...@googlegroups.com
Are your ids ObjectIds or strings? Assuming ObjectId,

db.collection.find( { 'favouriteSubscribers.$id': ObjectId("4f8b593c3a4b0b045e000039") } )

No need for $regex. But make sure you spell the field name correctly, with a $: favouriteSubscribers.$id
Reply all
Reply to author
Forward
0 new messages