【问题标题】:How to push object to an existing array in MongoDB如何将对象推送到 MongoDB 中的现有数组
【发布时间】:2023-01-18 18:09:56
【问题描述】:

我想弄清楚如何将新对象推送到 Go 中的数组。

我的数据库截图:

我需要在 actors 数组下推送一个新对象(此数组中的最大大小为 20 项)。

在 Node.js 中我会运行{ $push: { "actors": {$sort: {_id: 1}, $each: [{"name": "test"}], $slice: -20}} }

但是在 Go 中,我不确定它的正确语法是什么。

这是我的集合结构的定义方式:

type General struct {
ID              primitive.ObjectID  `bson:"_id"`
general         string              `bson:"general,omitempty"`
Actors []struct{
    ID          primitive.ObjectID  `bson:"_id"`
    name        string              `bson:"name,omitempty"`
}

}

**** 编辑 ****

重新生成 ObjectId:

我已经根据您的回答更新了我的代码:

    update := bson.D{{"$push", bson.D{{"actors", bson.D{{"$sort", bson.D{{"_id", 1}}}, {"$each", bson.A{bson.D{{"name", "test"}, {"_id", primitive.NewObjectId()}}}}, {"$slice", -20}}}}}}

但是当我运行代码时,出现以下错误:undefined: primitive.NewObjectId (exit status 2)

如果我只是运行 fmt.Println(primitive.NewObjectID()) 然后我可以看到一个新的 ObjectId 被打印出来......所以我试图弄清楚为什么它在更新查询中不起作用。

(我导入了"go.mongodb.org/mongo-driver/bson/primitive"

【问题讨论】:

    标签: mongodb go


    【解决方案1】:

    您可以使用“go.mongodb.org/mongo-driver/bson”包中的bson primitives构建update document or pipeline

    使用 NewObjectID function in the primitive package 生成一个 ObjectId。

    import (
        "fmt"
        "context"
        "go.mongodb.org/mongo-driver/bson/primitive"
    )
    //...
    
    update := bson.D{{"$push", bson.D{{"actors", bson.D{{"$sort", bson.D{{"_id", 1}}}, {"$each", bson.A{bson.D{{"name", "test"}, {"_id", primitive.NewObjectId()}}}}, {"$slice", -20}}}}}}
    

    然后针对您的收藏运行更新管道。

    import (
        "fmt"
        "context"
        "go.mongodb.org/mongo-driver/bson"
    )
    
    //...
    filter := bson.D{{"_id", 12333}}
    result, err := collection.UpdateOne(context.Background(), filter, update)
    

    【讨论】:

    • 太好了,这似乎运作良好!还有一个问题,如何在插入新的actor时默认创建_id?再次感谢
    • @YoniMayer 很高兴一切顺利。我更新了我的答案以包括如何为演员生成新的 ObjectId。
    猜你喜欢
    • 2020-05-21
    • 2016-03-05
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    相关资源
    最近更新 更多