phpmongodbphp-mongodb

PHP Mongo Search in Subdocument Key only


I want to to fetch row in Mongo on matching the subdocument in PHP Mongo.I want to achive result like

mysql query :- users like '"14:"' or invoice_id ="2"`

My structure in Mongo is

"invoice_id":0,"users":{"14":"2022-06-09 10:56:10","212":"2022-06-09 04:05:35"},
"invoice_id":2,"users":{"15":"2022-06-09 10:56:10","246":"2022-06-09 04:05:35"},    

I want to fetch users = "14":

I tried PHP Mongo Query

$data["users.0"] = new MongoDB\BSON\Regex("14");
$result = $collection->find($data, $option);    

The problem is - it search in value. I want to search in key only.

Please guide.


Solution

  • The solution was "$exists"

    $data["users.14"] =   ['$exists' => true];
    $result = $collection->find($data, $option);
    

    This gives search result with Key "14"