登录
首页 >  Golang >  Go问答

替换 MongoDB 中的文档:使用 Go 驱动程序的方法

来源:stackoverflow

时间:2024-02-20 21:30:26 463浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《替换 MongoDB 中的文档:使用 Go 驱动程序的方法》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我正在尝试使用 mongodb/mongo-go-driver 更新 mongodb 中的文档。从其文档来看,一个文档可以替换为:

var coll *mongo.collection
var id primitive.objectid

// find the document for which the _id field matches id and add a field called "location"
// specify the upsert option to insert a new document if a document matching the filter isn't found
opts := options.replace().setupsert(true)
filter := bson.d{{"_id", id}}
replacement := bson.d{{"location", "nyc"}}
result, err := coll.replaceone(context.todo(), filter, replacement, opts)
if err != nil {
    log.fatal(err)
}

if result.matchedcount != 0 {
    fmt.println("matched and replaced an existing document")
    return
}
if result.upsertedcount != 0 {
    fmt.printf("inserted a new document with id %v\n", result.upsertedid)
}

但是如果我的字段超过 20 个怎么办?我想知道是否可以更新而无需再次重写所有字段,我尝试了这样的操作:

// Replacement struct
type Input struct {
    Name        *string `json:"name,omitempty" bson:"name,omitempty" validate:"required"`
    Description *string `json:"description,omitempty" bson:"description,omitempty"`
    Location    *string `json:"location,omitempty" bson:"location,omitempty"`
}

... 
oid, _ := primitive.ObjectIDFromHex(id) // because 'id' from request is string
filter := bson.M{"_id", oid} // throws `[compiler] [E] missing key in map literal`
//                      ^^^
replacement := bson.D{{"$set", input}} // throws `composite literal uses unkeyed fields`
//                             ^^^^^
result, err := coll.ReplaceOne(context.TODO(), filter, replacement, opts)
...

但它会在过滤和替换时引发错误。如何正确替换整个文档?


解决方案


bson.M是一个地图,所以如果使用的话,就得写:bson.m{"_id": oid}。参见missing type in composite literal go AND missing key in map literal go

bson.D是一个结构体切片,所以如果使用它,应该写成bson.d{{key:"$set", value: input}}。省略字段名称不是编译器错误,这只是一个 go vet 警告。

现在开始更换。替换必须是文档本身,不能使用$set(这不是更新而是替换)。有关参考,请参阅 mongodb 的 collection.replaceOne() 和驱动程序的文档:Collection.ReplaceOne()

替换参数必须是将用于替换所选文档的文档。它不能为零,也不能包含任何更新运算符 (https://docs.mongodb.com/manual/reference/operator/update/)。

所以这样做:

filter := bson.m{"_id": oid}
result, err := coll.replaceone(context.todo(), filter, input, opts)

这是完整的代码。这将有助于读者理解代码流程。

func UpdateFunction(echoCtx echo.Context) (error) {

//Web Section
    documentID := echoCtx.Param("id")   //Provided in URL

    var newObject myStruct
    err := echoCtx.Bind(&newObject)  // Json with updated values sent by web client mapped to struct

    ctx := echoCtx.Request().Context()

//Database Section
    database := db.Conn.Database("myDatabase")
    collection := database.Collection("myCollection")

    existingHexID, err := primitive.ObjectIDFromHex(documentID)

    if err != nil {
        fmt.Println("ObjectIDFromHex ERROR", err)
    } else {
        fmt.Println("ObjectIDFromHex:", existingHexID)
    }

    // Replacing OLD document with new using _id
    filter := bson.M{"_id": newDocumentID}
    result, err := collection.ReplaceOne(ctx, filter, newObject)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf(
        "insert: %d, updated: %d, deleted: %d /n",
        result.MatchedCount,
        result.ModifiedCount,
        result.UpsertedCount,
    )

    return echoCtx.JSON(http.StatusOK, result.ModifiedCount)
}

到这里,我们也就讲完了《替换 MongoDB 中的文档:使用 Go 驱动程序的方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>