[GODRIVER-2505] Update array element by index not work as expected Created: 28/Jul/22  Updated: 27/Oct/23  Resolved: 19/Aug/22

Status: Closed
Project: Go Driver
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Nam Truong Le Assignee: Preston Vasquez
Resolution: Gone away Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Summary

Updating array element by index adds new property to all elements with index as part of the property name

How to Reproduce

Let's assume we have this structure:

{
  "foos": [{
    "bar": "value 1"
  }, {
    "bar": "value 2"
  }]
}

If we want to change "value 2" to "value 3", we can update in mongo console:

.updateOne({_id: new ObjectId("***")}, {"$set": {"foos.1.bar":"value3"}});

It works perfectly. But if I do the same thing in golang:

.UpdateOne(ctx, bson.M{"_id": someID}, bson.A{
		bson.M{
			"$set": bson.M{
				"foos.1.bar":"value 3",
			},
		},
	})

This will result:

{
  "foos": [{
    "bar": "value 1",
    "1": {"bar": "value 3"}
  }, {
    "bar": "value 2",
    "1": {"bar": "value 3"}
  }]
}

Would you mind checking this? Thank you



 Comments   
Comment by PM Bot [ 19/Aug/22 ]

There hasn't been any recent activity on this ticket, so we're resolving it. Thanks for reaching out! Please feel free to comment on this if you're able to provide more information.

Comment by Preston Vasquez [ 04/Aug/22 ]

vietnamvisa.dev@gmail.com, in your case the update argument should be presented as a document. Try the below code:

.UpdateOne(ctx, bson.D{{"_id": someID}}, bson.D{{"$set", bson.D{{"foos.1.bar","value 3"}}}})

This would be the Go driver's analogue of the mongo server's

.updateOne({_id: new ObjectId("***")}, {"$set": {"foos.1.bar":"value3"}}); 

The following:

.UpdateOne(ctx, bson.M{"_id": someID}, bson.A{bson.M{"$set": bson.M{"foos.1.bar":"value 3"}}} 

Would be equivalent to wrapping the update argument as an array, which is treated as an aggregation pipeline where the first stage is to set some data.

.updateOne({_id: new ObjectId("***")}, [{"$set": {"foos.1.bar":"value3"}}]); 

Comment by Esha Bhargava [ 29/Jul/22 ]

vietnamvisa.dev@gmail.com  Thank you for reporting this issue! We'll look into it and get back to you soon.

Generated at Thu Feb 08 08:38:47 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.