Tomislav Tomi Nikolic
Tomislav Tomi Nikolic

Reputation: 638

Inner join to mongoDB in PHP

Alright so I am trying to get this query translated into MongoDB from MySQL as I need it to optimize my data, but so far I haven't achieved nothing...

MySQL query

SELECT notifications.entity_id 
FROM notifications
INNER JOIN discussions
ON notifications.entity_id = discussions._id 
WHERE notifications.subscribers = 1

No matter what I try I can't seem to get even close to JOIN another table... I've done it simple way in PHP but it's causing a lot of headaches due to low to none optimization...

public function getData($userId) {

    $wheres =   ['subscribers' => $userId];
    $data   =   $this->get($wheres, ['entity_id']); # works for notifications table that I have predefined for this function

    $wheres =   ['_id' => $data['_id']];
    $data  =   $this->get_discussions($wheres, []); #queries discussions table

    return $data;
}

Upvotes: 1

Views: 144

Answers (1)

amku91
amku91

Reputation: 1038

My solution for this mysql query is this

db.notifications.aggregate({
    {$match : {subscribers : 1}},
    $lookup:{
        from:"discussions",
        localField:"entity_id",
        foreignField:"id",
        as:"entityids"
    },
    { "$unwind": "$entityids" }
})

Run this on mongo shell. You can fire this in PHP code also by using php methods. Hope this will help you.

Upvotes: 1

Related Questions