为了账号安全,请及时绑定邮箱和手机立即绑定

如何删除 Mongodb / Golang 中的数组项?

如何删除 Mongodb / Golang 中的数组项?

Go
慕村9548890 2021-12-07 18:57:48
我有以下数据结构,我试图从“艺术家”数组中删除一个项目。[    {        "id": "56b26eeb4a876400011369e9",        "name": "Ewan Valentine",        "email": "ewan@test.com",        "artists": [            "56b26f334a876400011369ea",            "56b2702881318d0001dd1441",            "56b2746fdf1d7e0001faaa92",        ],        "user_location": "Manchester, UK"    }]这是我的功能...// Remove artist from userfunc (repo *UserRepo) RemoveArtist(userId string, artistId string) error {    change := bson.M{"artists": bson.M{"$pull": bson.ObjectIdHex(artistId)}}    fmt.Println(userId)    err := repo.collection.UpdateId(bson.ObjectIdHex(userId), change)    return err}我收到以下错误:{  "_message": {    "Err": "The dollar ($) prefixed field '$pull' in 'artists.$pull' is not valid for storage.",    "Code": 52,    "N": 0,    "Waited": 0,    "FSyncFiles": 0,    "WTimeout": false,    "UpdatedExisting": false,    "UpsertedId": null  }}
查看完整描述

1 回答

?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

$pull运营商在更新语句的“顶级”操作,所以只需有这周围的错误的方式:

    change := bson.M{"$pull": bson.M{"artists": bson.ObjectIdHex(artistId)}}

更新运算符的顺序始终是运算符第一,动作第二。

如果在“顶级”键上没有运算符,MongoDB 会将其解释为只是一个“普通对象”来更新和“替换”匹配的文档。因此,关于$密钥名称中的错误。


查看完整回答
反对 回复 2021-12-07
  • 1 回答
  • 0 关注
  • 147 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信