【问题标题】:What is the bson syntax for $set in UpdateOne for the official mongo-go-driver官方 mongo-go-driver 的 UpdateOne 中 $set 的 bson 语法是什么
【发布时间】:2019-04-07 23:29:09
【问题描述】:

我正在尝试熟悉官方mongo-go-driverUpdateOne 的正确语法。

我最简单的完整示例如下:

(注意:为了使用此代码,您需要替换为您自己的用户名和服务器名,并将登录密码作为 MONGO_PW 导出到环境):

package main

import (
    "context"
    "fmt"
    "os"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/primitive"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type DB struct {
    User       string
    Server     string
    Database   string
    Collection string
    Client     *mongo.Client
    Ctx        context.Context
}

var db = DB{
    User:       <username>,
    Server:     <server_IP>,
    Database:   "test",
    Collection: "movies",
    Ctx:        context.TODO(),
}

type Movie struct {
    ID          primitive.ObjectID `bson:"_id" json:"id"`
    Name        string             `bson:"name" json:"name"`
    Description string             `bson:"description" json:"description"`
}

func main() {
    if err := db.Connect(); err != nil {
        fmt.Println("error: unable to connect")
        os.Exit(1)
    }
    fmt.Println("connected")

    // The code assumes the original entry for dunkirk is the following
    // {"Name":"dunkirk", "Description":"a world war 2 movie"}
    updatedMovie := Movie{
        Name:        "dunkirk",
        Description: "movie about the british evacuation in WWII",
    }

    res, err := db.UpdateByName(updatedMovie)
    if err != nil {
        fmt.Println("error updating movie:", err)
        os.Exit(1)
    }
    if res.MatchedCount < 1 {
        fmt.Println("error: update did not match any documents")
        os.Exit(1)
    }
}

// UpdateByName changes the description for a movie identified by its name
func (db *DB) UpdateByName(movie Movie) (*mongo.UpdateResult, error) {
    filter := bson.D{{"name", movie.Name}}

    res, err := db.Client.Database(db.Database).Collection(db.Collection).UpdateOne(
        db.Ctx,
        filter,
        movie,
    )
    if err != nil {
        return nil, err
    }
    return res, nil
}

// Connect assumes that the database password is stored in the
// environment variable MONGO_PW
func (db *DB) Connect() error {
    pw, ok := os.LookupEnv("MONGO_PW")
    if !ok {
        fmt.Println("error: unable to find MONGO_PW in the environment")
        os.Exit(1)
    }
    mongoURI := fmt.Sprintf("mongodb+srv://%s:%s@%s", db.User, pw, db.Server)

    // Set client options and verify connection
    clientOptions := options.Client().ApplyURI(mongoURI)
    client, err := mongo.Connect(db.Ctx, clientOptions)
    if err != nil {
        return err
    }
    err = client.Ping(db.Ctx, nil)
    if err != nil {
        return err
    }

    db.Client = client
    return nil
}

包文档中UpdateOne 的函数签名是:

func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, 
    update interface{}, opts ...*options.UpdateOptions) (*UpdateResult, error)

所以我显然在为函数创建 update interface{} 参数时犯了某种错误,因为我遇到了这个错误

error updating movie: update document must contain key beginning with '$'

最受欢迎的答案here 表明我需要使用类似这样的文档

{ $set: {"Name" : "The Matrix", "Decription" "Neo and Trinity kick butt" } }

但逐字逐句,这不会在 mongo-go-driver 中编译。

我认为我需要某种形式的 bson 文档来符合 Go 语法。为update 创建此 bson 文档的最佳和/或最有效的语法是什么?

【问题讨论】:

    标签: mongodb go


    【解决方案1】:

    在玩了一会儿之后,我通过在上面的代码中更改 UpdateByName 函数,使用 mongodb bson package 解决了 A LOT OF TRIAL AND ERROR 之后的问题如下:

    // UpdateByName changes the description for a movie identified by its name
    func (db *DB) UpdateByName(movie Movie) (*mongo.UpdateResult, error) {
        filter := bson.D{{"name", movie.Name}}
        update := bson.D{{"$set",
            bson.D{
                {"description", movie.Description},
            },
        }}
    
        res, err := db.Client.Database(db.Database).Collection(db.Collection).UpdateOne(
            db.Ctx,
            filter,
            update,
        )
        if err != nil {
            return nil, err
        }
        return res, nil
    }
    

    注意bson.D{{$"set", ... 的使用。不幸的是 MongoDB 实现 bson 包的方式仍然没有通过验证。如果有人有评论来解决下面的 lint 冲突,我们将不胜感激。

    go.mongodb.org/mongo-driver/bson/primitive.E composite literal uses unkeyed fields
    

    【讨论】:

    • 我们如何更新整个movie 字段而不提及更新文档中的每个字段?
    • 这就是我实现更新过滤器的方式 -- update := bson.D{primitive.E{Key: "$set", Value: bson.D{ primitive.E{Key: "name ",值:supplier.Name},primitive.E{Key:"documentType",值:supplier.DocumentType} },}}
    • @sumedhe,如果您想替换整个文档,而不仅仅是某些字段,您可能需要考虑使用 ReplaceOne() 而不是 UpdateOne()
    • @shontauro,请写一个答案并提供一些细节。这将对读者有所帮助。评论里的代码很难看懂。
    【解决方案2】:

    在许多情况下,您可以替换构造

    filter := bson.D{{"name", movie.Name}}
    

    filter := bson.M{"name": movie.Name}
    

    如果参数顺序不重要

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      • 2019-04-06
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      相关资源
      最近更新 更多