yii2 mongodb-如何在集合子数组中查找元素

时间:2019-01-31 18:03:01

标签: mongodb yii2 nosql

集合中的数组看起来像这样。

$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
                    )

            )
     )

)        

我可以找到子数组的特定行中是否存在某些Mac,像这样:

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

但是我需要检查子数组的任何行中是否存在某些mac,因此需要代替一些行索引0,而是使用星号或其他内容。 怎么做 ?

1 个答案:

答案 0 :(得分:1)

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

$results = $query->all();