codexy
codexy

Reputation: 413

yii2 mongodb - how to find element in collection subarray

Array from collection looks like this.

$result = $collection->find();

Array
(
[0] => Array
    (
        [_id] => MongoDB\BSON\ObjectId Object
            (
                [oid] => 5c52b90454851c44aa2987e2
            )

        [name] => Array
            (
                [date] => 2019-01-31 10:59:48
                [value] => DESKTOP-TODTF5E
            )

        [network_addresses] => Array
            (
                [0] => Array
                    (
                        [ip_1] => 12.21.134
                        [ip_2] => 50
                        [mac] => xx:xx:xx:xx:xx:xx
                    )

                [1] => Array
                    (
                        [ip_1] => 192.168.0
                        [ip_2] => 2
                        [mac] => yy:yy:yy:yy:yy:yy
                    )

            )
     )

)        

I can find if some mac exist in specific row of sub array like this:

$result = $collection->find(["network_addresses.0.mac" => 
"xx:xx:xx:xx:xx:xx"]);

But I need to check if certain mac exists in any row of subarray, so instead of row index 0 I need to put some asterix or something. How to do that ?

Upvotes: 0

Views: 219

Answers (1)

Tomislav Nekic
Tomislav Nekic

Reputation: 225

$query = (new Query)->select(["name"])
         ->from(['db_name','collection_name'])
         ->where(["network_addresses" => [ '$elemMatch' =>['mac' => "xx:xx:xx:xx:xx:xx"]]]);

$results = $query->all();

Upvotes: 1

Related Questions