My structure is something like this:
{
"_id": "13hu13o13uuo1",
"profiles": {
"1": [1,2,3],
"847891": [3, 4],
..
}
}
"profiles" is an "object-array"/dictionary that has dynamic keys and their values are arrays.
How can I update all profile elements, inserting, let's say, 11 in every array?
Version: Mongo 4.2.3
CodePudding user response:
You can use an aggregation pipeline with a $merge
stage, to achieve this:
db.collection.aggregate([
{
"$addFields": {
"profiles": {
"$arrayToObject": {
"$map": {
"input": {
"$objectToArray": "$profiles"
},
"as": "element",
"in": {
k: "$$element.k",
v: {
"$concatArrays": [
"$$element.v",
[
11
]
]
}
}
}
}
}
}
},
{
"$merge": {
"into": "collection",
"on": "_id",
"whenMatched": "replace",
}
}
])
Playground link.
CodePudding user response:
While the syntax for the other answer is technically correct, I recommend not using the aggregation pipeline $merge
approach for most usecases. The main reason is that such a pipeline is not atomic.
You can simply execute the exact same logic using the aggregation pipeline update feature, hence gaining the atomic property of the update operations in Mongo.
Here's how this looks:
db.collection.updateMany(
{},
[
{
"$set": {
"profiles": {
"$arrayToObject": {
"$map": {
"input": {
"$objectToArray": "$profiles"
},
"as": "element",
"in": {
k: "$$element.k",
v: {
"$concatArrays": [
"$$element.v",
[
11
]
]
}
}
}
}
}
}
}
])