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

标签 mongodb go mongodb-query mgo

我有以下数据结构,我正在尝试从“艺术家”数组中删除一个项目。

[
    {
        "id": "56b26eeb4a876400011369e9",
        "name": "Ewan Valentine",
        "email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d786a7c735d69786e69337e7270" rel="noreferrer noopener nofollow">[email protected]</a>",
        "artists": [
            "56b26f334a876400011369ea",
            "56b2702881318d0001dd1441",
            "56b2746fdf1d7e0001faaa92",
        ],
        "user_location": "Manchester, UK"
    }
]

这是我的功能...

// Remove artist from user
func (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
  }
}

最佳答案

$pull运算符是更新语句中的“顶级”运算符,因此您只是以错误的方式进行操作:

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

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

如果“顶级”键上没有运算符,MongoDB 会将其解释为“普通对象”来更新和“替换”匹配的文档。因此, key 名称中的 $ 出现错误。

关于mongodb - 如何删除 Mongodb/Golang 中的数组项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35247241/

相关文章:

mysql - 如何将 Node.js/passport 合并到我的网站中?

mysql - 哪个最适合我的需求 : MongoDB, CouchDB 或 MySQL。相关定义的标准

node.js - 如何将输入数组保存到嵌套 Mongoose 模式中的子模式?

mongodb - 如何查找并合并mongodb文档

go - Go标准库中的最大堆和最小堆

memory - 如何将内存地址(如 0xc20803a000)转换为字符串?戈朗

Node.js : How to return Object in Query Aggregation?

reactjs - 在 Gorilla Mux : 403 error on POST request 中配置 CORS

MongoDB:在具有未知键的对象中查找给定字段值的文档

mongodb - 将值转换为键 mongodb 聚合