We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

populate two collection in mongodb

I have two collection is :

//collection Logs

+--------+-----+
|  user  | content
+--------+-----+
|  user1 | content 1
|  user1 | content 2
|  user3 | content 3
+----+-----+

// collection Account

+--------+-----+
|  user  | avatar
+--------+-----+
|  user1 | default.jpg   
|  user2 | user2.jpg
|  user3 | default.jpg
+----+-----+

When i use logs::find() how to i can get 'avatar' of user from collection Account, Thanks



2.5k

You should be able to find the relevant account using something like this:

$logs = logs::find()

foreach( $logs as $log ){

    $account = Account::find( [
        [ 'user' => $log->user  ]
    ] );

    // You can now access $account->avatar

}

If this is going to be something that is access frequently in your application you should also ensure that user is an index in your mongo DB and perhaps even look at some sort of caching solution.



1.5k

You should be able to find the relevant account using something like this:

$logs = logs::find()

foreach( $logs as $log ){

  $account = Account::find( [
      [ 'user' => $log->user  ]
  ] );

  // You can now access $account->avatar

}

If this is going to be something that is access frequently in your application you should also ensure that user is an index in your mongo DB and perhaps even look at some sort of caching solution.

Thanks sir, but you have any way better.. Why we don't left join as mysql



2.5k
Accepted
answer

Thanks sir, but you have any way better.. Why we don't left join as mysql

Mongo doesn't support joins as each collection its a whole document. Pulling pieces from each row such as a relational database defeats the purpose of using a noSQL database.

From the document here https://docs.mongodb.org/ecosystem/tutorial/model-data-for-ruby-on-rails/

bear in mind that MongoDB collections are not equivalent to relational tables; each serves a unique design objective. A normalized table provides an atomic, isolated chunk of data. A document, however, more closely represents an object as a whole.

Cheers Ben