如何在MongoDB中用更新操作符拼接字符串并新增不存在字段?
MongoDB 实现字段存在则拼接、不存在则新增赋值
执行以下MongoDB操作后,_id为1的文档因transcript字段不存在,使用$concat更新后该字段值为null;而_id为2的文档成功完成字符串拼接。现需实现:若transcript字段不存在则新增并设置值为[bot]: hi human,若存在则在原有内容后拼接该字符串。
原操作代码
db.students4.deleteMany({}) db.students4.insertMany( [ { "_id" : 1, "quizzes" : [ 4, 6, 7 ] }, { "_id" : 2, "quizzes" : [ 5 ], transcript: "[user]: hi" }, ] ) db.students4.find() db.students4.updateOne( { "_id": 1 }, [{ $set: { transcript: { $concat: ["$transcript", "\n[bot]: hi human"], }, }, }], { upsert: true } ); db.students4.updateOne( { "_id": 2 }, [{ $set: { transcript: { $concat: ["$transcript", "\n[bot]: hi human"], }, }, } ]); db.students4.find()
原执行结果
[ { _id: 1, quizzes: [ 4, 6, 7 ], transcript: null }, { _id: 2, quizzes: [ 5 ], transcript: '[user]: hi\n[bot]: hi human' } ]
解决方案
问题出在$concat遇到null值时会直接返回null,因此需要先处理字段不存在的情况。以下两种方法均可实现需求:
方法1:用$ifNull替换空字段为空白字符串
当transcript字段不存在时,将其视为空白字符串再进行拼接,这样不存在字段的文档会直接得到目标字符串(无多余换行):
// 统一处理两个文档,无需分开执行updateOne db.students4.updateMany( { _id: { $in: [1, 2] } }, [{ $set: { transcript: { $concat: [ { $ifNull: ["$transcript", ""] }, "\n[bot]: hi human" ] } } }] );
方法2:用$cond精准判断字段是否存在
通过$exists判断字段是否存在,分别执行拼接或赋值逻辑,逻辑更清晰:
db.students4.updateMany( { _id: { $in: [1, 2] } }, [{ $set: { transcript: { $cond: { if: { $exists: ["$transcript", true] }, then: { $concat: ["$transcript", "\n[bot]: hi human"] }, else: "[bot]: hi human" } } } }] );
修正后执行结果
[ { _id: 1, quizzes: [ 4, 6, 7 ], transcript: '[bot]: hi human' }, { _id: 2, quizzes: [ 5 ], transcript: '[user]: hi\n[bot]: hi human' } ]
内容的提问来源于stack exchange,提问作者Gianfranco P
相关产品推荐
相关产品推荐

