doudianhuo1129 2016-02-06 22:24
浏览 172
已采纳

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

I have the following data structure, and I'm attempting to remove an item from the 'artists' array.

[
    {
        "id": "56b26eeb4a876400011369e9",
        "name": "Ewan Valentine",
        "email": "ewan@test.com",
        "artists": [
            "56b26f334a876400011369ea",
            "56b2702881318d0001dd1441",
            "56b2746fdf1d7e0001faaa92",
        ],
        "user_location": "Manchester, UK"
    }
]

Here's my function...

// 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
}

I'm getting the following error:

{
  "_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条回答 默认 最新

  • dpbfb7119 2016-02-06 22:35
    关注

    The $pull operator is a "top level" operator in update statements, so you simply have this the wrong way around:

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

    The order of update operators is always operator first, action second.

    If there is no operator at the "top level" keys, MongoDB interprets this as just a "plain object" to update and "replace" the matched document. Hence the error about the $ in the key name.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵