【问题标题】:How to project an item in an array to the top level and also fetch only the matched objects in the array如何将数组中的项目投影到顶层并仅获取数组中的匹配对象
【发布时间】:2021-06-29 19:59:43
【问题描述】:

目前这是我的salesOrder 集合中的一个数据集示例

{
    "totalCost": 4,
    "salesOrderRef": "s4",
    "customerRef": "c10",
    "date": "2021-06-03T00:00:00.000Z",
    "etd": "2021-06-24T00:00:00.000Z",
    "delivered": true,
    "paid": false,
    "inventory": [{
        "sku": "i3",
        "quantity": 1,
        "priceEa": 2,
        "discount": "0"
    }, {
        "sku": "i2",
        "quantity": 2,
        "priceEa": 2,
        "discount": 2
    }]
}

如何让它匹配

{
    "salesOrderRef": "s4",
    "customerRef": "c10",
    "sku": "i3",
    "quantity": 1,
    "priceEa": 2,
    "discount": "0"
}

如果我搜索sku: i3? 如果在单个salesOrder 文档的库存数组中有任何重复的sku,我还希望它复制另一个结果,例如

{
    "salesOrderRef": "s4",
    "customerRef": "c10",
    "sku": "i3",
    "quantity": 1,
    "priceEa": 2,
    "discount": "0"
},
{
    "salesOrderRef": "s4",
    "customerRef": "c10",
    "sku": "i3",
    "quantity": 3,
    "priceEa": 4,
    "discount": "0"
}

我怎样才能做到这一点?我尝试使用聚合和过滤器,但我不确定如何

【问题讨论】:

    标签: node.js mongodb aggregation-framework


    【解决方案1】:

    试试这个聚合查询,据我了解,这应该会给你你提到的输出文档。

    db.collection.aggregate([
    
      {
        $unwind: "$inventory"
           },   {
        $project: {
        "_id" : 0,
        "salesOrderRef": 1,
        "customerRef": 1,
        "sku": "$inventory.sku",
        "quantity": "$inventory.quantity",
        "priceEa": "$inventory.priceEa",
        "discount": "$inventory.discount"
        }   
    }, ])
    

    【讨论】:

    • 非常感谢!!放松是完美的,我不得不进一步项目,然后再次匹配以再次将其过滤为仅sku: i3
    猜你喜欢
    • 2018-11-23
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 2020-08-31
    • 2021-11-27
    • 2018-11-13
    • 2015-07-13
    相关资源
    最近更新 更多