Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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



1.7k

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.

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

```php $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



1.7k
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 http://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