我有一个名为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值。
问题
sku获得MongoDB值吗?sku更有效?发布于 2018-09-09 02:57:10
是的,实际上。您可以使用投影:
// 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库而有所不同。
https://stackoverflow.com/questions/52240756
复制相似问题