合并数组数据,并通过对字段执行乘法来添加一些附加字段



我有以下类型的模式

Mongo游乐场

问题——我想把所有成功的交易和他们各自的用户放在列表中,并为特定的交易提供一些额外的字段,比如奖励。就像如果在10中支付金额,则奖励将是0.3倍->3.但我需要0.3,如果第一次成功付款,其他人只需要0.1。

尝试:我已经实现了部分输出,无法获得基于第一笔交易的奖励计算

输出将为-

[
{
_id: 1,
name: 'Stephen',
transactions: [
{
_id: 1,
paidAmount: 10,
reward: 3
},
{
_id: 3,
paidAmount: 20,
reward: 2
}
]
},
{
_id: 2,
user: 'Peter',
transactions: [
{
_id: 2,
paidAmount: 5,
reward: 0.15
}]
}
]

嗨,我已经找到了上述的解决方案

db.users.aggregate([
{
$match: {
_id: 1,

},

},
{
$lookup: {
from: "payments",
localField: "_id",
foreignField: "user",
as: "payments",

},

},
{
$addFields: {
transactions: {
$reduce: {
input: "$payments",
initialValue: [],
in: {
$concatArrays: [
"$$value",
{
$filter: {
input: "$$this.transactions",
cond: {
$eq: [
"$$this.status",
"succeeded"
]
},

},

},

],

},

},

},

},

},
{
$project: {
transactions: {
$map: {
input: "$transactions",
as: "t",
in: {
paidAmount: "$$t.paidAmount",
status: "$$t.status",
createdAt: "$$t.createdAt",
reward: {
$cond: {
if: {
$eq: [
{
$indexOfArray: [
"$transactions",
"$$t"
]
},
0
]
},
then: {
$multiply: [
"$$t.paidAmount",
0.3
]
},
else: {
$multiply: [
"$$t.paidAmount",
0.1
]
},

},

},

},

},

},

},

},
{
$project: {
id: {
$toString: "$_id"
},
totalAMount: {
$sum: "$transactions.paidAmount"
},
totalReward: {
$sum: "$transactions.reward"
},
transactions: "$transactions",

},

},

])

如果您找到了更好的解决方案/方法,请发表评论。

试试这个

最新更新