Juraj Ivan
Juraj Ivan

Reputation: 493

Find documents based on referenced ID in MongoDB & PHP

i've got referenced Users collection object in my MongoDB Items collection. Random Item document looks like this:
ps: to clarify, i really dont want to embed Items into Users collection.

Array
        (
            [_id] => MongoId Object
                (
                    [$id] => 4d3c589378be56a008000000
                )
            [modified] => 1295800467
            [order] => 1
            [title] => MyFirstItem
            [user] => Array
                (
                    [$ref] => users
                    [$id] => MongoId Object
                        (
                            [$id] => 4d3c55e7a130717c09000012
                        )
                )
        )
So i need to find only items, which are assigned to the specific user. Find this question of my problem, but the solution didnt work for me. MongoDB-PHP: JOIN-like query

Here is snippet of my code, givin' me no results at all.

$user = $db->users->findOne(array("_id" => new MongoID("4d3c55e7a130717c09000012")));
$items = $db->items->find(array("user" => array('$id' => $user["_id"])));
What is the correct way to finding that data? Should i instead put an user_id as a MongoID without reference?

Spent all my day with this, thanks in advance!

Upvotes: 2

Views: 5118

Answers (1)

pingw33n
pingw33n

Reputation: 12510

Try

$items = $db->items->find(array("user.$id" => $user["_id"]));

Upvotes: 1

Related Questions