Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何删除Mongodb/Golang中的数组项?_Mongodb_Go_Mongodb Query_Mgo - Fatal编程技术网

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

如何删除Mongodb/Golang中的数组项?,mongodb,go,mongodb-query,mgo,Mongodb,Go,Mongodb Query,Mgo,我有以下数据结构,我正试图从“艺术家”数组中删除一个项目 [ { "id": "56b26eeb4a876400011369e9", "name": "Ewan Valentine", "email": "ewan@test.com", "artists": [ "56b26f334a876400011369ea", "56b2702881318d0001dd1441",

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

[
    {
        "id": "56b26eeb4a876400011369e9",
        "name": "Ewan Valentine",
        "email": "ewan@test.com",
        "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
  }
}
该运算符在update语句中是“顶级”运算符,因此您的方法是错误的:

    change := bson.M{"$pull": bson.M{"artists": bson.ObjectIdHex(artistId)}}
更新运算符的顺序始终是运算符第一,操作第二


如果“顶级”键上没有操作符,MongoDB将其解释为一个“普通对象”,用于更新和“替换”匹配的文档。因此键名中的
$
出现错误。

完美!非常感谢你!