Reputation: 936
In Mongo DB, how can I set values in an array of arrays when the index cannot be assumed?
For example, how can I set the IdleShutdown value to "2" (instead of "10") in this blob below?
What would the command look like to correctly find the item in the list and set the value without any assumptions that the current index will stay the same? I also cannot assume any values for the second item in the list (eg, "10" could become any value)
> db.EventPluginSettingsCollection.findOne({"_id": "spot"})
{
"_id" : "spot",
"LastWriteTime" : ISODate("2019-12-16T11:04:30.499Z"),
"Name" : "Spot",
"PluginEnabled" : 1,
"DebugLogging" : false,
"Icon" : null,
"Limits" : [ ],
"DlInit" : [
[
"State",
"Disabled"
],
[
"Config",
"{}"
],
[
"IdleShutdown",
"10"
],
[
"StaggerInstances",
"50"
],
[
"PreJobTaskMode",
"Conservative"
],
[
"AWSInstanceStatus",
"Disabled"
]
],
"Meta" : {
}
}
I understand I could replace the whole blob, and I could also use individual indexes for each item, but none of these approaches are future proof should the number of items in the list change in the future.
Upvotes: 0
Views: 293
Reputation: 3421
MongoDB 3.6 introduced the filtered positional operator array update operator, $[ < identifier> ], for these types of operations. Updates using this syntax will only update elements of an array that match a specified array filter.
For example:
> db.foo.update(
... { "_id" : "spot" },
... {
... "$set" : {
... // only updates array elements matching the filter below
... "DlInit.$[element]" : [ "IdleShutdown", "2"]
... }
... },
... {
... "arrayFilters": [
... // Search for DlInit array elements that are the specified array
... { "element.0" : "IdleShutdown" }
... ]
... }
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.foo.find().pretty()
{
"_id" : "spot",
"LastWriteTime" : ISODate("2019-12-16T11:04:30.499Z"),
"Name" : "Spot",
"PluginEnabled" : 1,
"DebugLogging" : false,
"Icon" : null,
"Limits" : [ ],
"DlInit" : [
[
"State",
"Disabled"
],
[
"Config",
"{}"
],
[
"IdleShutdown",
"2"
],
[
"StaggerInstances",
"50"
],
[
"PreJobTaskMode",
"Conservative"
],
[
"AWSInstanceStatus",
"Disabled"
]
],
"Meta" : {
}
}
Upvotes: 1