Let's say a have a simple document:
{
array: ["a", "b", "c", "d"]
}
How to modify the second value in aggregation?
With update
it is very simple:
db.collection.updateOne({},
{ $set: { "array.1": "B" } }
)
gives:
{
array: ["a", "B", "c", "d"]
}
In aggregation framework you can use this one:
db.collection.aggregate([
{
$set: {
"array": {
$map: {
input: "$array",
in: {
$cond: {
if: { $eq: [{ $indexOfArray: ["$array", "$$this"] }, 1] },
then: "B",
else: "$$this"
}
}
}
}
}
}
])
However, this fails when the array is not a Set, i.e. values are not unique like this one
{
array: ["a", "b", "c", "b"]
}