聚合以创建具有嵌套文档值的文档

Aggregate to create documents with values of a nested document

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

我的输入collection:

  {
    "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
}

其中商店等于代码,价格等于基础,sale_price 等于促销,item_id 等于 Id,数量等于输入 collection 的数量。

到目前为止我做了什么:

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

我尝试使用 $unwind 但没有成功。如果可能的话,我怎样才能使用简单的聚合来获得预期的输出。正如我之前所说,我正在使用 pyMongo 来执行此聚合

  • $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