我的invoices
集合如下所示:
[
{
inv_name: "Client 1",
inv_date: 2022-12-20T05:09:09.803Z,
inv_ready: false,
inv_payments: [
{
id: "123",
pay_amount: 32.45
},
{
id: "456",
pay_amount: 55.60
}
]
},
{
inv_name: "Client 2",
inv_date: 2022-12-19T05:09:09.803Z,
inv_ready: true,
inv_payments: [
{
id: "459",
pay_amount: 67.45
},
{
id: "556",
pay_amount: 30.60
}
]
}
]
我知道如何使用$project
和$unwind
创建一个子文档数组,目标是像这样从父文档向每个对象添加一些数据。
[
{
"client": "Client 1",
"pay_amount": 32.45,
"pay_date": "123"
},
{
"client": "Client 1",
"pay_amount": 55.6,
"pay_date": "456"
},
{
"client": "Client 2",
"pay_amount": 67.45,
"pay_date": "459"
},
{
"client": "Client 2",
"pay_amount": 30.6,
"pay_date": "556"
}
]
下面是我的尝试:
db.invoices.aggregate([
{
"$project": {
_id: 0,
"inv_payments": {
$reduce: {
input: "$inv_payments",
initialValue: [],
in: {
$concatArrays: [
[
{
client: "$this.name",
pay_id: "$$this.id",
pay_amount: "$$this.pay_amount"
}
],
"$inv_payments"
]
}
}
}
}
},
{
$unwind: "$inv_payments"
},
{
$replaceRoot: {
newRoot: "$inv_payments"
}
}
])
我想我已经接近了。我不确定错误在哪里。任何想法都将不胜感激!
1条答案
按热度按时间6vl6ewon1#
除了注解中提到的打字错误,你使用
$reduce
操作符的方式也不正确,你没有使用累加器变量($$value
)。不要使用
$reduce
,而是使用$map
运算符,这在您的场景中更为简单:溶液1:
$map
Demo (
$map
) @ Mongo Playground解决方案2:
$reduce
对于
$reduce
运算符,您的查询应为:Demo (
$reduce
) @ Mongo Playground