1

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;
}
Tomislav Tomi Nikolic
  • 608
  • 3
  • 10
  • 15
  • 1
    Possible duplicate of [How do I perform the SQL Join equivalent in MongoDB?](https://stackoverflow.com/questions/2350495/how-do-i-perform-the-sql-join-equivalent-in-mongodb) or [mongodb php - how to do “INNER JOIN”-like query](https://stackoverflow.com/questions/3829638/mongodb-php-how-to-do-inner-join-like-queryb) – Raymond Nijland Aug 24 '18 at 13:08

1 Answers1

1

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.

amku91
  • 1,010
  • 11
  • 21