globalsign / mgo

The MongoDB driver for Go
Other
1.97k stars 231 forks source link

UpdateAll - Can I update multiple different records #342

Closed Emixam23 closed 5 years ago

Emixam23 commented 5 years ago

Hi !

I am coming because I would like to know how can update mutliple records with the same request. I have this code that makies me able to update one document based on a given id

func UpdateByID(session *mgo.Session, documentName string, id *bson.ObjectId, item interface{}) error {
    _session := session.Copy()
    defer _session.Close()
    collection := _session.DB(constants.DBName).C(documentName)
    return collection.Update(bson.M{"_id": id}, item)
}

Now I have this one to update multiple documents:

func UpdateByIDs(session *mgo.Session, documentName string, ids []*bson.ObjectId, items interface{}) error {
    _session := session.Copy()
    defer _session.Close()
    collection := _session.DB(constants.DBName).C(documentName)
    _, err := collection.UpdateAll(bson.M{"_id": bson.M{"$in": ids}}, items)
    return err
}

However I am getting the following:

BSON field 'update.updates.u' is the wrong type 'array', expected type 'object'

I am using the code above like this:

err = odm.UpdateByIDs(session, eventDocument, ids, &events)

Any idea? I've been stuck since a couple of days but didn't find the time to ask for help :)

Thanks for any help

eminano commented 5 years ago

Hi @Emixam23,

We use the issue tracker to track bugs with mgo - if you have a usage question, it's best to try Stack Overflow :)

This example of use from the tests might be helpful though: https://github.com/globalsign/mgo/blob/master/changestreams_test.go#L358

Thanks! Esther

Emixam23 commented 5 years ago

Hey :)

Thanks for your help, sorry for asking then :) I will give it a try, thanks again

Max