【发布时间】:2023-03-31 15:08:01
【问题描述】:
我正在尝试通过使用 go 来学习 mongodb。 我试图将数组推送到 mongodb 的空数组。
首先,我创建了一个这样的集合。
{
"_id" : ObjectId("60c6c2d7b64d7f9d461d2bd5"),
"title" : "Test Title",
"description" : "This is test vote title",
"candidates" : [
{
"name" : "Test Name",
"score" : 0,
"voter" : []
}
]
}
这是我用于 db 的类型
type Vote struct {
Title string
Description string
Candidates []Candidate
}
type Candidate struct {
Name string
Score int
Voter []Supporter
}
type Supporter struct {
UUID string
Name string
}
而且,我想要做的是,将数组对象推送到空数组'voter'。 我想将此对象推送到数据库。
[]vote.Supporter{{UUID: uuid.NewString(), Name: "Test User A"}, {UUID: uuid.NewString(), Name: "Test User B"}}
然后,我用这个命令推送这个数组对象。
vote.VoteToSubject(collection, "Test Title", "Test Name", []vote.Supporter{{UUID: uuid.NewString(), Name: "Test User A"}, {UUID: uuid.NewString(), Name: "Test User B"}})
func VoteToSubject(collection *mongo.Collection, title string, name string, voter []Supporter) {
// filter := bson.D{{"title", title}, {"candidates", bson.D{{"name", name}}}}
filter := bson.D{{"$and", []interface{}{bson.D{{"title", title}}, bson.D{{"candidates.name", name}}}}}
update := bson.D{{"$set", bson.D{{"candidates.votes", voter}}}}
updateResult, err := collection.UpdateOne(context.TODO(), filter, update)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)
}
我所期望的是,数组对象被添加到投票空数组中(而不是替换)。
{
"_id" : ObjectId("60c6c2d7b64d7f9d461d2bd5"),
"title" : "Test Title",
"description" : "This is test vote title",
"candidates" : [
{
"name" : "Test Name",
"score" : 0,
"voter" : [
{
"uuid" : *uuid1*
"name" : *name1*
}, {
"uuid" : *uuid2*
"name" : *name2*
},
]
}
]
}
但是该命令返回一个错误......就像这样。
ekfkal79@DARAMI-PC MINGW64 ~/go/src/github.com/ekfkal79/go-mongo-db (main)
$ go run main.go
Connected to MongoDB!
2021/06/14 11:45:52 multiple write errors: [{write errors: [{Cannot create field 'votes' in element {candidates: [ { name: "Test Name", score: 0, voter: [] } ]}}]}, {<nil>}]
exit status 1
我不知道如何解决这个问题...我阅读了 mongodb 的文档,但它没有帮助... 我需要你的帮助...
对不起,我的英语水平不好......
【问题讨论】:
标签: arrays database mongodb go mongodb-query