【问题标题】:Can I push array object to empty array on mongodb? (using go)我可以将数组对象推送到 mongodb 上的空数组吗? (使用去)
【发布时间】: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


    【解决方案1】:

    是的,我解决了我的问题!

    问题是,我没有指定数组的索引!!

    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{{"$addToSet", bson.D{{"candidates.$.voter", bson.D{{"$each", 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)
    }
    

    在变量“update”中,我将数组的索引指定为“$”。然后使用'$each'查询非结构化数组'voter'!

    {
        "_id" : ObjectId("60c6c2d7b64d7f9d461d2bd5"),
        "title" : "Test Title",
        "description" : "This is test vote title",
        "candidates" : [ 
            {
                "name" : "Test Name",
                "score" : 0,
                "voter" : [ 
                    {
                        "uuid" : "92b5eff2-b4de-4b48-96d8-9ea41a74c22b",
                        "name" : "Test User A"
                    }, 
                    {
                        "uuid" : "f50037ec-d898-4b6e-a836-7cc44e306493",
                        "name" : "Test User B"
                    }
                ]
            }
        ]
    }
    

    效果很好!!

    谢谢大家!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 2021-07-20
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      相关资源
      最近更新 更多