【发布时间】: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