Search in embedded documents

8 views
Skip to first unread message

sune brodersen

unread,
Aug 31, 2010, 4:38:21 PM8/31/10
to mongodb-user
Hi,

Im new to Mongo, and facing a problem in searching. Im using php and
inserting the following document:

$doc = array('firstname'=>'sune',
'clicks'=>array(array('url'=>'blabla','tstamp'=>33235435334543),array('url'=>'blabla2','tstamp'=>4536546456)));

$col->insert($doc);

This works fine. And if i search for specifik url like this:

$col-
>find(array('clickstrem.url'=>'blabla','clickstream.tstamp'=>33235435334543)

it returns the doc from above. This is all fine. But if i search like
this:

$col->find(array('clicks.url'=>'blabla','clicks.tstamp'=>4536546456)

it also returns the doc from above. It kind of make sense, since the
first entry in the embedded doc has url=>blabla, and the second entry
has tstamp=>4536546456

But what im looking for is a way to search for docs that includes
url=blabla and tstamp=4536546456 in the same entry in the embedded
doc.

Hope it makes sense :)

BR/Sune

Michael Dirolf

unread,
Aug 31, 2010, 4:41:15 PM8/31/10
to mongod...@googlegroups.com
What you need is to use the $elemMatch operator for your query.
Basically allows you to group criteria that all need to match the
_same_ embedded doc. GIve that a shot and let us know if you still
have questions.

> --
> You received this message because you are subscribed to the Google Groups "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.
>
>

sune brodersen

unread,
Aug 31, 2010, 5:03:28 PM8/31/10
to mongodb-user
Hi Michael,

Thanks for the fast answer!

Just what i needed - nice

One question. Will this be categoriesed as a slow search?

/Sune

Michael Dirolf

unread,
Aug 31, 2010, 5:12:12 PM8/31/10
to mongod...@googlegroups.com
Depends on your definition of a slow search ;). $elemMatch should use
an index to filter the results to all of the results that match if
$elemMatch weren't there, but will then scan to pick out the ones that
match on the same element.
Reply all
Reply to author
Forward
0 new messages