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' }
]
I would like to insert [bot]: hi human
to the first document (_id
= 1
)
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' }
]
I would like to insert [bot]: hi human
to the first document (_id
= 1
)
2 Answers
Reset to default 1db.students4.updateOne(
{ "_id": 1 },
[{
$set: {
transcript: {
$cond: {
if: { $eq: [{ $type: "$transcript" }, "missing"] },
then: "[bot]: hi human",
else: { $concat: ["$transcript", "\n[bot]: hi human"] }
}
}
}
}],
);
This does the job :)
If you replace the first updateOne()
with that ^, you get this:
db.students4.find()
[
{ _id: 1, quizzes: [ 4, 6, 7 ], transcript: '[bot]: hi human' },
{ _id: 2, quizzes: [ 5 ], transcript: '[user]: hi\n[bot]: hi human' }
]
Instead of a type-check like in your answer, you can also use $ifNull
and default to an empty string if it's missing/null.
db.students4.update(
{ "_id": 1 },
[
{
$set: {
transcript: {
$concat: [
{ $ifNull: ["$transcript", ""] },
"\n[bot]: hi human"
]
}
}
}
]
)
Mongo Playground 1A
If the extra \n
at the start is not wanted when it's missing, use ifNull with concat or default. The concat part will be null when it's missing/null so then the default will be just the text you want to add:
db.students4.update(
{ "_id": 1 },
[
{
$set: {
transcript: {
$ifNull: [
{ $concat: ["$transcript", "\n[bot]: hi human"] },
"[bot]: hi human"
]
}
}
}
]
)
Mongo Playground 1B
You can also do a bulk update for all documents where it's missing/null, and set it ""
. Then future queries won't need $cond
or $ifNull
checks every time.
db.students4.update(
{ transcript: null },
{ $set: { transcript: "" } }
)
Mongo Playground 2