mongodb updateOne 如何修改查询数组结果中的第一项?
我的数据是这样的:
我想通过 updateOne 更改 prizes 数组中的第一个 8.8,我的代码是这样的:
let email = 'aa@bb.com'
let money = '8.8'
mongoserve.updateOne({
_id: data[0]._id
}, {
$set: { // 更新值,prize 为遍历变量
'prizes.$[prize]': {
email: email,
prize: money
}
}
}, {
arrayFilters: [ // 匹配值
{ 'prize': { $eq: money } }
]
}).then(data => {
res.send('抽奖成功')
}).catch(error => {
console.error(error)
})
但更新会将数组中两个 8.8 都修改掉我尝试再 prizes.$[prize] 后面再追加 .$ 或 .1 结果都是报错
还望指点如何更新结果(数组)的第一个匹配项呢?
当然笨办法是先通过遍历将 prizes 修改好,之后赋给 updateOne 修改,但目前自己不想这么做
回复
1个回答

test
2024-07-02
let email = 'aa@bb.com';
let money = '8.8';
mongoserve.findOne({
_id: data[0]._id
}).then(doc => {
let index = doc.prizes.findIndex(prize => prize == money);
// 构建一个更新操作符
let updateOperator = { $set: {} };
updateOperator.$set['prizes.' + index] = {
email: email,
prize: money
};
// 用这个索引去进行更新操作
return mongoserve.updateOne({
_id: data[0]._id
}, updateOperator);
}).then(data => {
res.send('抽奖成功');
}).catch(error => {
console.error(error);
});
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容