looking for some help building the update query to the element index of the docItemArray (given a match on the docItemArray_id) field and then a match on am innerItems innerItems_id field.
Hi Shmuel,
You can utilise MongoDB update operator $[\] (available in MongoDB v3.6+). Especially have a look at the example Update Nested Arrays in Conjunction with $[].
Using your sample document structure above, with MongoDB Go driver you can achieve the desired outcome with the following example:
collection := client.Database("dbname").Collection("collname")
// Set arrayfilters variables x and y
arrayFilters := options.ArrayFilters{
Filters: bson.A{bson.M{"x.docItemArray_id":"0000XSNJG0MQJHBF4QX73HGXVC"}, bson.M{"y.innerItems_id":1},
}}
updateOptions := options.UpdateOptions{}
updateOptions.SetArrayFilters(arrayFilters)
// Set the location of the nested array and the updated value
updateSet := bson.M{"$set": bson.M{
"docItemArray.$[x].innerItems.$[y]":
bson.M{"innerItems_id": 1, "newField1":"newValue1", "newField2":"newValue2"},
}}
result, err := collection.UpdateOne(context.Background(), bson.M{}, updateSet, &updateOptions)
Although you may be able to achieve the desired operation with this nested embedded fields, I would suggest to reconsider your document structure/schema. You should utilise the flexible schema structure characteristic of MongoDB to make operations easy for majority (if not all) of your database operations. Please see Schema Design: Summary for more information on schema design.
Regards,
Wan.
--
You received this message because you are subscribed to the Google Groups "mongodb-go-driver" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-go-dri...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-go-driver/0981f802-f3e8-4d58-bb1b-1447342e58fd%40googlegroups.com.