Access the items in array in db

Hello, I have created a document, in Mongodb compass it looks like:

{
meeting_name: "it is a test meeting name"
to: Array
   0: Object
      contact: Object
           phone:"+33123456789"
   1: Object
      contact: Object
           phone:"+33987654321"
}

The field “to” is an array of object contact, where the object contact is a map, with key value pares like “phone”: “+33123456789”. I want to do something like: find the contact with phone “+33123456789”, set the name of the contact to be “john doe”, so that the data looks like:

{
meeting_name: "it is a test meeting name"
to: Array
   0: Object
      contact: Object
           phone:"+33123456789"
           name: "john doe"
   1: Object
      contact: Object
           phone:"+33987654321"
}

how can I implement this function by golang driver?

Thanks for the help,

James

I have examples of updates in mongo-go-examples/update_test.go at master · simagix/mongo-go-examples · GitHub. The title is misleading because I don’t see any array in action.

Hello Ken, thanks for the quick answer. The data looks like:

{ 
   "to": [
      {"contact":{"phone":"+33123456789"}},
      {"contact":{"phone":"+33987654321"}}
   ]
}

I want to change it to:

{ 
   "to": [
      {"contact":{"phone":"+33123456789", "name":"john doe"}},
      {"contact":{"phone":"+33987654321"}}
   ]
}

I plan to search the contact object with phone is “+33123456789”, then add a pair "name":"john doe" to it, how can I do this?

Thanks,

james

I added below to update_test.go

func TestUpdateArray(t *testing.T) {
	var err error
	var client *mongo.Client
	var ctx = context.Background()
	if client, err = getMongoClient(); err != nil {
		t.Fatal(err)
	}
	doc := bson.M{"to": []bson.M{
		bson.M{"contact": bson.M{"phone": "+33123456789"}},
		bson.M{"contact": bson.M{"phone": "+33987654321"}},
	}}
	defer client.Disconnect(ctx)
	collection := client.Database("test").Collection("foo")
	collection.DeleteMany(ctx, bson.M{})
	collection.InsertOne(ctx, doc)

	var filter bson.M
	json.Unmarshal([]byte(`{"to": { "$elemMatch": {"contact.phone": "+33123456789"} } }`), &filter)
	var update bson.M
	json.Unmarshal([]byte(`{"$set": {"to.$.contact.name": "John Doe"} }`), &update)
	if _, err = collection.UpdateOne(ctx, filter, update); err != nil {
		t.Fatal(err)
	}
}

Hello Ken,

That’s exactly what I need! Thank you so much!

James