首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在子数组中逐字段查找文档,并在同一子数组中返回另一个字段。

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

Stack Overflow用户
提问于 2018-09-09 02:02:28
回答 1查看 34关注 0票数 0

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

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

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

简化的集合如下所示:

代码语言:javascript
复制
[
    "_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"
        ]
]

我正在检索正确的文档

代码语言:javascript
复制
// 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. 但是有什么方法可以用sku获得MongoDB值吗?
  2. 在最后一步中使用MongoDB有什么好处吗?还是只使用PHP循环查找sku更有效?
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-09 02:57:10

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

代码语言:javascript
复制
// 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库而有所不同。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52240756

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档