我正在尝试创建管道以根据条件添加字段:
我有一个名为helped的字段,该字段将包含一个ID列表,我要做的是添加一个字段,具体取决于给定ID是否在该数组内
数据结构的示例可能是这样:
{
helpful: [ 5ecd62230a180f0017dc5342 ],
verifiedPurchase: false,
_id: 5f789010e07e4033342c7307,
title: 'text',
body: 'text',
rating: 3,
user: {
_id: 5ecd62230a180f0017dc5342,
name: 'store11',
picture: 'pictureurl'
},
replies: [],
updatedAt: 2020-10-03T18:04:48.026Z,
createdAt: 2020-10-03T14:52:00.410Z,
helpfulCount: 1,
helpfulForMe: false
},
我已经尝试过使用此管道
{
$addFields:{
helpfulForMe: {
$cond: {
if: {"$in":[user, "$helpful"] } ,
then: true,
else: false,
}
}
}
},
还有这个
"$addFields": {
"helpfulForMe" : {
"$in":[
['5ecd62230a180f0017dc5342'], "$helpful"
]
}
}
},
但是即使我设置了匹配的ID,两者都返回false
我希望从你们那里得到良好的解决。谢谢
答案 0 :(得分:0)
您可以尝试是否输入的是ID数组,
$reduce
迭代有用数组的循环并检查条件,如果用户数组中的id则返回true,否则返回false let user = ["5ecd62230a180f0017dc5342"];
{
$addFields: {
helpfulForMe: {
$reduce: {
input: "$helpful",
initialValue: false,
in: {
$cond: [{ $in: ["$$this", user] }, true, "$$value"]
}
}
}
}
}