Search code examples
phpmongodbmongodb-queryjenssegers-mongodb

Querying a collection with an array of mongoID


I have the following code:

// company_ids is an array of mongo IDs
// company_id is an array (with only 1 element) of mongo ID
foreach($company_ids as $company_id){
    $results = Archive::where("billing.company._id", 'all', array($company_id))->get();
    ...

Here is the output of Log::info(print_r($company_ids, true))

[2016-10-22 02:41:27] production.INFO: Array
(
    [0] => 57515764b91a8c4d008b45d1
    [1] => 57515764b91a8c4d008b45d6
    [2] => 57515764b91a8c4d008b45db
    [3] => 57515764b91a8c4d008b45e0
    ...
)

How can I query the Archive collection directly using company_ids and removing the need for the foreach loop?


Solution

  • A small update in @Robbie answer. No need to use an array of MongoIds simply use array of string and it will work. Am using this only with laravel-jenessengers

    $company_ids = [
        '57515764b91a8c4d008b45d1',
        '57515764b91a8c4d008b45d6',
        '57515764b91a8c4d008b45db',
        '57515764b91a8c4d008b45e0'
    ]
    
    $results = Archive::whereIn('billing.company._id', $company_ids)->get();