Reputation: 553
Trying to update a document in MongoDB using the official mongo driver,go.mongodb.org/mongo-driver/mongo
this is my struct that I want to update
type Activity struct {
Timestamp time.Time `bson:"timestamp,omitempty"`
Type string `bson:"type,omitempty"`
}
type Member struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
Name string `bson:"name,omitempty"`
Activities []Activity `bson:"activities ,omitempty"`
}
this is the code for updating document
filter := bson.M{"_id": m.ID}
update := bson.M{
"$set": bson.M{
"name": m.Name,
},
"$each": bson.M{"activities": m.Activities },
}
res, err := coll.UpdateOne(ctx, filter, update)
the name gets updated but nothing happens with the activities
what am I doing wrong? should I use ReplaceOne instead?
Upvotes: 0
Views: 840
Reputation: 18835
the name gets updated but nothing happens with the activities
This is because $each array update operator is designed to be used with $addToSet (append unique) or $push(append).
For example, if you would like to update the array with no duplicate activities the set:
update := bson.M{
"$set": bson.M{
"name": obj.Name,
},
"$addToSet": bson.M{"activities": bson.M{"$each": obj.Activities }},
}
cursor, err := collection.UpdateOne(context.Background(), filter, update )
Upvotes: 2