How using $pushAll in go with mgo

huangapple go评论82阅读模式
英文:

How using $pushAll in go with mgo

问题

我这样存储结构体:

type Test struct {
    Key  string
    Tags []string
}

在 MongoDB 中,我想要更新 Tags 字段并添加一些其他的标签。我找到了 $pushAll,但是我不知道如何使用它。

我尝试了以下代码:

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

但是出现了错误。

英文:

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.

答案1

得分: 5

操作符,如$set$push甚至$pushAll,定义了语句的“更新”部分的操作。这些是“顶级”操作符,因此您在更新语句的“根”级别上定义它们,并将要操作的字段作为其子级:

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

然而,从MongoDB 2.6开始,$pushAll操作符被视为已弃用。该功能已与$each修饰符合并,该修饰符还适用于$addToSet

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

从MongoDB 2.4开始,$push操作符可用,最新版本的区别在于省略了$slice修饰符,该修饰符在早期版本中也是必需的。除非您需要支持旧版本,否则通常建议改用$each修饰符以实现未来的兼容性。

英文:

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.

huangapple
  • 本文由 发表于 2014年8月13日 10:02:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/25276942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定