【问题标题】:Find document by field in sub-array and return another field in same sub-array在子数组中按字段查找文档并返回同一子数组中的另一个字段
【发布时间】:2019-02-13 21:11:03
【问题描述】:

我有一个名为 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 更有效?

【问题讨论】:

  • $item_id = some_id_127'; 那里缺少报价,回答你的问题你可以使用投影和聚合查询,可能还有一点 JS。我必须查一下,但这是可能的。所以答案是——1. 是的,2. 对其进行基准测试。
  • docs.mongodb.com/manual/reference/operator/aggregation-pipeline 如果您查看项目,基本上它会创建一个临时文档,您可以编辑架构以添加新字段(您的总数)。

标签: php arrays mongodb nested


【解决方案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 的文档,其中只有与您搜索的元素匹配的元素。

确切的语法可能因驱动程序版本以及您是否使用用户空间库而异。

【讨论】:

    猜你喜欢
    • 2017-03-28
    • 2018-11-05
    • 2021-09-30
    • 1970-01-01
    • 2021-07-01
    • 2016-04-23
    • 1970-01-01
    • 2015-04-24
    • 2013-08-26
    相关资源
    最近更新 更多