Search code examples
mongodbgomgo

How using $pushAll in go with mgo


I store like this struct

type Test struct {
    Key string
    Tags []string
}

in mongodb, Then i want update tags add some another tags, I found $pushAll, But i can't how to using it.

I Try

mongoDb.C("test").Update(
    bson.M{"key": key},
    bson.M{"$set": bson.M{"tags": bson.M{"$pushAll": tags}}}
)

But it's error.


Solution

  • Operators like $set and $push and even $pushAll define the actions for the "update" portion of the statement. These are "top level" operators so you define them at the "root" level of the update statement with the fields to operate on as it's children:

    mongoDb.C("test").Update(
        bson.M{"key": key}, 
        bson.M{"$pushAll": bson.M{"tags": tags}}
    )
    

    As of MongoDB 2.6 though the $pushAll operator is considered deprecated. The functionality has been merged with the $each modifier, which also works with $addToSet:

    mongoDb.C("test").Update(
        bson.M{"key": key}, 
        bson.M{"$push": bson.M{"tags": bsonM.{"$each": tags} }}
    )
    

    The operator is available for $push as of MongoDB 2.4, where the difference in latest versions being the omission of the $slice modifier which is also required with earlier releases. Unless you need to support legacy versions it is generally recommended to use the $each modifier instead for future compatibility.