mongodb-queryphp-mongodb

PHP Mongo Multiple "AND" using "find" method


I am trying to fetch data with "AND" condition but its not matching all conditions. I want to fetch result only when all conditions match.

My conditions are :-    

$and1 = array( '$and' => array(
                    array( "users.23315" => array( '$exists' => true ) ) ,                   
                  ));   
                  
        $and2 = 
            array( '$and' => array(
                    array('messages.message' => new MongoDB\BSON\Regex("2019"))));      
        
        $where = array( '$and' => array( $and1, $and2) );
    
    $client = new MongoDB\Client(CONNECTION_STRING);
    $db = $client->sample;
    $collection = $client->sample->$db_name ;   
    $result = $collection->find($where);

THE ISSUE IS NOT MATCHING ALL CONDITIONS. THE OUTPUT SHOULD CONDITION BOTH "2019" & "users.23315". But its not. Result is   

Array
(
    [0] => Array
        (       
            
            [users] => Array
                (
                    [23315] => 2022-06-28 13:07:54
                )

            [messages] => Array
                (
                    [0] => Array
                        (
                            
                            [message] => 2019 Test data                             
                            [user_id] => 23315
                        )

                )            
        )

    [1] => Array
        (                
            [users] => Array
                (
                    [23236] => 2021-12-16 12:49:17
                    [23315] => 2021-12-19 11:27:11
                )
            [messages] => Array
                (
                    [0] => Array
                        (
                           
                            [message] => Another row message
                            [direction] => 0
                            [user_id] => 23315
                        )

                )             
        )


You can see, the ARRAY[1] is matching only  "users.23315" exist true. The Message array is not having "2019". How can I force to include that ?

Solution

  • Solution for multiple "AND was

    $where =   ['$and' => [
                                    ["users.$user_id" => ['$exists' => true]],
                                    ['messages.type' => 'whatsapp'],
                                    ['delete' => ['$ne' =>   1]],
                                ]
                ];  
    

    This applied "And" condition for all conditions. Required result