英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论