在子数组中按字段查找文档,并在同一子数组中返回另一个字段

时间:2018-09-09 02:02:29

标签: php arrays mongodb nested

我有一个名为products的集合,该集合包含包含多个字段的文档以及一个variants子数组。

variants子数组具有多个字段,包括skuid

我知道id的值,我需要使用它来获取sku的值。

简化的集合如下所示:

[
    "_id"      => "whatever_id_1",
    "field_2"  => "some value 1",
    "variants" => 
        [
            "id"  => "some_id_123"
            "sku" => "SKU-1"
        ],
        [
            "id"  => "some_id_124"
            "sku" => "SKU-2"
        ],
        [
            "id"  => "some_id_125"
            "sku" => "SKU-3"
        ]
],
[
    "_id"      => "whatever_id_2",
    "field_2"  => "some value 2",
    "variants" => 
        [
            "id"  => "some_id_126"
            "sku" => "SKU-4"
        ],
        [
            "id"  => "some_id_127"
            "sku" => "SKU-5"
        ],
        [
            "id"  => "some_id_128"
            "sku" => "SKU-6"
        ]
],
[
    "_id"      => "whatever_id_3",
    "field_2"  => "some value 3",
    "variants" => 
        [
            "id"  => "some_id_129"
            "sku" => "SKU-7"
        ],
        [
            "id"  => "some_id_130"
            "sku" => "SKU-8"
        ],
        [
            "id"  => "some_id_131"
            "sku" => "SKU-9"
        ]
]

我正在使用

检索正确的文档
// Set item_id
$item_id = 'some_id_127';
// Build 'find product with inventory item id' query
$find_product_with_id_query = [ 'variants' => ['$elemMatch' => ['id' => $item_id] ] ];
// Get the product document to process 
$inventory_update_product = $client_products_collection->findOne($find_product_with_id_query);

这将正确返回带有"_id" => "whatever_id_2"的父文档。

现在,我知道我可以遍历该结果(例如$inventory_update_product['variants'),并以此方式找到sku的值。

问题
1.但是,是否可以通过MongoDB获得sku值?
2.在最后一步中使用MongoDB有什么好处,还是仅使用PHP for循环来找到sku更有效率?

1 个答案:

答案 0 :(得分:1)

是的,实际上。您可以使用投影:

// Set item_id
$item_id = 'some_id_127';

// Build 'find product with inventory item id' query
$find_product_with_id_query = [ 'variants' => ['$elemMatch' => ['id' => $item_id] ] ];

// Project and limit options
$options = [
    'projection' => [ 'variants.$' => 1 ],
    'limit' => 1
];

// Get the product document to process 
$inventory_update_product = $client_products_collection->find($find_product_with_id_query, $options);

这将返回一个游标,其中包含带有数组variants的文档,且该元素仅与您搜索的元素匹配。

确切的语法可能会有所不同,具体取决于驱动程序版本以及您是否正在使用userland库。