我有一个名为products
的集合,该集合包含包含多个字段的文档以及一个variants
子数组。
variants
子数组具有多个字段,包括sku
和id
。
我知道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
更有效率?
答案 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库。