Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query (find many) documents from multiple collections with the same document structure (MongoDB & PHP)

I use MongoDB PHP v1.3 and in my MongoDB I have multiple collections:

// COLLECTION NAMES:
- user_1_list_1
- user_1_list_2
- user_1_list_3
...
- user_1_list_55

All these collections have the same document-structure:

{
   first_name
   last_name
   phone
}

How can I query the documents from all of these collections at the same time? In the documentation, it is explained how to query (find many) documents from one collection: https://docs.mongodb.com/php-library/v1.3/tutorial/crud/#find-many-documents.

For example, in my case, it would look something like this:

$collection_name = "user_1_list_1";
$collection = $this->db->{$collection_name};

$query = []; 

$cursor = $collection->find(
    $query,
    [
        'limit' => 10,
        'skip'  => 0,
        'sort'  => ['first_name' => 1],
    ]
);

... but this will find documents only from one collection (in this case, only from the collection with name "user_1_list_1").

How to find documents from all of these collections (user_1_list_1, user_1_list_2, user_1_list_3 ... ) (that have the same structure), not just from one specific? Is this possible at all? If yes, how would you do that?

like image 437
PeraMika Avatar asked May 27 '19 17:05

PeraMika


1 Answers

MongoDB is not a relation database and there is no good solution for your case.

  1. You can get your collections and loop over it (but it’s a not good solution).
  2. You can change your database structure and use one collection with embedded data
like image 125
andranikasl Avatar answered Oct 05 '22 21:10

andranikasl