如何删除 Mongodb / Golang 中的数组项?
How do I remove an array item in Mongodb / Golang?
我有以下数据结构,我正在尝试从 'artists' 数组中删除一个项目。
[
{
"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
}
}
$pull
运算符是更新语句中的 "top level" 运算符,因此您只是用错了方法:
change := bson.M{"$pull": bson.M{"artists": bson.ObjectIdHex(artistId)}}
更新运算符的顺序始终是运算符在前,操作在后。
如果 "top level" 键处没有运算符,MongoDB 将其解释为仅 "plain object" 更新和 "replace" 匹配的文档。因此,关于键名中的 $
的错误。
我有以下数据结构,我正在尝试从 'artists' 数组中删除一个项目。
[
{
"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
}
}
$pull
运算符是更新语句中的 "top level" 运算符,因此您只是用错了方法:
change := bson.M{"$pull": bson.M{"artists": bson.ObjectIdHex(artistId)}}
更新运算符的顺序始终是运算符在前,操作在后。
如果 "top level" 键处没有运算符,MongoDB 将其解释为仅 "plain object" 更新和 "replace" 匹配的文档。因此,关于键名中的 $
的错误。