【问题标题】:Aggregate to create documents with values of a nested document聚合以创建具有嵌套文档值的文档
【发布时间】:2021-12-13 05:50:03
【问题描述】:

我想使用 pyMongo 创建一个聚合文档,它通过嵌套文档的每个值生成一个文档。

我的输入集合:

  {
    "Id" : "12345-7",
    "Price: 
    {
            "Base" : "9.99",
            "Promo" : "7.99"
    },
    "Stock" : [ 
            {
                "Code" : "1",
                "Qty" : 1.0
            }, 
            {
                "Code" : "3",
                "Qty" : 7.0
            }
        ]
    }
    { 
    "Id" : "22222-0",
    "Price: 
    {
            "Base" : "2.99",
            "Promo" : "2.99"
    },
    "Stock" : [ 
            {
                "Code" : "3",
                "Qty" : 10.0
            }, 
            {
                "Code" : "5",
                "Qty" : 1.0
            },
            {
                "Code" : "10",
                "Qty" : 2.0
            }
         ]
    }

我预期的聚合输出:

{
item_id : "12345-7",
store: "1",
price : 9.99,
quantity : 1,
sale_price: 7.99,
}
{
item_id : "12345-7",
store: "3",
price : 9.99,
quantity : 7,
sale_price: 7.99
}
{
item_id : 22222-0",
store: "3",
price : 2.99,
quantity : 10,
sale_price: 2.99
}
{
item_id : 22222-0",
store: "5",
price : 2.99,
quantity : 1,
sale_price: 2.99
}
{
item_id : 22222-0",
store: "10",
price : 2.99,
quantity : 2,
sale_price: 2.99
}

其中 store 等于 code,price 等于 base,sales_price 等于 promo,item_id 等于 Id,quantity 等于输入集合中的 Qty。

到目前为止我做了什么:

db.getCollection('File').aggregate([
{
    "$project" :
    {
        "price" : "$Price.Base",
        "sale_price" : "$Price.Promo",
        "item_id" : "$Id",
        "Stock" : 1
    }
},
{
    "$unset" : "Price"  
}
])

我尝试使用$unwind,但没有成功。如果可能的话,如何使用简单的聚合获得预期的输出。就像我之前说的,我正在使用 pyMongo 来执行这个聚合

【问题讨论】:

    标签: mongodb nosql aggregation-framework pymongo


    【解决方案1】:
    • $unwind
    • $project
    db.collection.aggregate([
      {
        "$unwind": "$Stock"
      },
      {
        "$project": {
          item_id: "$Id",
          store: "$Stock.Code",
          price: "$Price.Base",
          quantity: "$Stock.Qty",
          sale_price: "$Price.Promo",
          
        }
      }
    ])
    

    mongoplayground

    【讨论】:

      猜你喜欢
      • 2018-07-14
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 2020-07-26
      • 2013-09-18
      • 2020-03-08
      相关资源
      最近更新 更多