doudianhuo1129
2016-02-06 22:24
浏览 122

如何在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
  }
}

图片转代码服务由CSDN问答提供 功能建议

我具有以下数据结构,并且正在尝试从“艺术家”数组中删除一项。 / p>

  [
 {
“ id”:“ 56b26eeb4a876400011369e9”,
“ name”:“ Ewan Valentine”,
“ email”:“ ewan@test.com  ”,
“艺术家”:[
“ 56b26f334a876400011369ea”,
“ 56b2702881318ddddddddd1”,
“ 56b2746fdf1d7e0001faaa92”,
],
“用户位置”:“英国曼彻斯特” 
} 
] 
    
 
 

这是我的功能...

  ///从用户中删除艺术家
func(回购* UserRepo)RemoveArtist(  userId字符串,artistId字符串)错误{
 change:= bson.M {“ artists”:bson.M {“ $ pull”:bson.ObjectIdHex(artistId)}} 
 fmt.Println(userId)
 err:  = repo.collection.UpdateId(bson.ObjectIdHex(userId),更改)
返回错误
} 
   
 
 

我遇到以下错误:

  {
“ _message”:{
“ Err”:“以美元($)为前缀的字段'$ pull'i  n'artists。$ pull'对存储无效。“,
”代码“:52,
” N“:0,
”等待“: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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题