问题
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"]
}
回答1:
You can loop over the $size(length) of the array using $range and then get the index of the element and can change the value of the index element to whatever you want.
db.collection.aggregate([
{ "$project": {
"array": {
"$map": {
"input": { "$range": [0, { "$size": "$array" }] },
"in": {
"$cond": [
{ "$eq": ["$$this", 1] },
"B",
{ "$arrayElemAt": ["$array", "$$this"] }
]
}
}
}
}}
])
MongoPlayground
回答2:
Another solution is to $unwind your array with includeArrayIndex and preserveNullAndEmptyArrays, set value with condition, then group. But beware, although it can be useful in some situations, it can consume more server resources in some cases.
db.collection.aggregate([
{
$unwind: {
path: "$array",
includeArrayIndex: "index",
preserveNullAndEmptyArrays: true
}
},
{
$addFields: {
array: {
$cond: {
if: {
$eq: [
"$index",
1
]
},
then: "B",
else: "$array"
}
}
}
},
{
$group: {
_id: "$_id",
array: {
$push: "$array"
}
}
}
])
you can test here
来源:https://stackoverflow.com/questions/60205337/how-to-modify-value-in-array-by-position-at-aggregation-framework