如何在MongoDB中更新quarterFinals数组内首个address为null的对象属性
MongoDB更新操作实现方案
适用MongoDB 4.2及以上版本(聚合管道更新,直接在数据库层完成操作)
直接执行如下更新语句即可完成需求:
// 注意替换下面的collection为你实际使用的集合名 db.collection.updateOne( // 匹配目标文档,可根据你的实际索引字段调整匹配条件 { "data.createTournament._id": ObjectId("613122d0c7befdeef3b0b571") }, [ { $set: { "data.createTournament.rounds.quarterFinals": { $map: { input: "$data.createTournament.rounds.quarterFinals", as: "item", in: { $let: { vars: { firstNull: { $eq: ["$$item.firstParticipant.address", null] }, secondNull: { $eq: ["$$item.secondParticipant.address", null] } }, in: { $cond: [ "$$firstNull", { $mergeObjects: [ "$$item", { firstParticipant: { $mergeObjects: ["$$item.firstParticipant", { address: "123" }] } } ] }, { $cond: [ "$$secondNull", { $mergeObjects: [ "$$item", { secondParticipant: { $mergeObjects: ["$$item.secondParticipant", { address: "123" }] } } ] }, "$$item" ] } ] } } } } } } } ] )
注:如果你的需求是仅更新整个数组中第一个出现的null address,后续的null值不修改,优先使用下方应用层操作的方案,逻辑更可控不易出错。
适用所有MongoDB版本(应用层操作,以Node.js环境为例)
先查询出目标文档,遍历修改后再提交更新,代码如下:
const { ObjectId } = require('mongodb') // 1. 查询目标文档 const targetDoc = await db.collection('你的集合名').findOne({ "data.createTournament._id": ObjectId("613122d0c7befdeef3b0b571") }) const quarterFinals = targetDoc.data.createTournament.rounds.quarterFinals let hasUpdated = false // 2. 遍历数组找到第一个address为null的项更新 for (const match of quarterFinals) { if (hasUpdated) break if (match.firstParticipant.address === null) { match.firstParticipant.address = '123' hasUpdated = true break } if (match.secondParticipant.address === null) { match.secondParticipant.address = '123' hasUpdated = true break } } // 3. 提交更新到数据库 await db.collection('你的集合名').updateOne( { "data.createTournament._id": ObjectId("613122d0c7befdeef3b0b571") }, { $set: { "data.createTournament.rounds.quarterFinals": quarterFinals } } )
内容的提问来源于stack exchange,提问作者Daywison Ferreira Leal
相关产品推荐
相关产品推荐

