mongodb-go-driver/bson 结构到 bson.Document 编码

2024-03-22

我正在与https://github.com/mongodb/mongo-go-driver https://github.com/mongodb/mongo-go-driver和 目前正在尝试实现此类结构的部分更新

type NoteUpdate struct {
    ID        string `json:"id,omitempty" bson:"_id,omitempty"`
    Title     string `json:"title" bson:"title,omitempty"`
    Content   string `json:"content" bson:"content,omitempty"`
    ChangedAt int64  `json:"changed_at" bson:"changed_at"`
}

例如,如果我有

noteUpdate := NoteUpdate{ Title: "New Title" }

然后我预计存储文档中唯一的“标题”字段将被更改。

我需要写一些类似的东西

collection.FindOneAndUpdate(context.Background(),
    bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)),
    // I need to encode non-empty fields here
    bson.NewDocument(bson.EC.SubDocument("$set", bson.NewDocument(...)))
)

问题是我不想手动编码每个非空字段bson.EC.String(...) or bson.EC.Int64(...)。我尝试使用bson.EC.InterfaceErr(...)但出现错误

无法创建类型 *models.NoteUpdate 的元素,请尝试使用 bsoncodec.ConstructElementErr

不幸的是,bsoncodec 中没有这样的功能。我发现的唯一方法是创建包装器

type SetWrapper struct {
    Set interface{} `bson:"$set,omitempty"`
}

并像这样使用它

partialUpdate := &NoteUpdate{
    ID: "some-note-id", 
    Title: "Some new title",
 }
updateParam := SetWrapper{Set: partialUpdate}
collection.FindOneAndUpdate(
    context.Background(),
    bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)),
    updateParam,
)

它可以工作,但是是否可以使用 bson/bsoncodec 文档生成器实现相同的目标?

UPD。我的问题的完整背景: 我编写了 REST 端点部分地更新“Note”文档(存储在 MongoDB 中)。我现在拥有的代码:

var noteUpdate models.NoteUpdate
ctx.BindJSON(&noteUpdate)    
//omit validation and errors handling
updateParams := services.SetWrapper{Set: noteUpdate}
res := collection.FindOneAndUpdate(
context.Background(),
bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)),
    updateParams,
    findopt.OptReturnDocument(option.After),
)

我想要的代码

var noteUpdate models.NoteUpdate
ctx.BindJSON(&noteUpdate)    
//omit validation and errors handling
res := collection.FindOneAndUpdate(
    context.Background(),
    bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)),
    bson.NewDocument(
        //bsoncodec.ConstructElement doesn't exists
        bsoncodec.ConstructElement("$set", &noteUpdate)),
        ),
    findopt.OptReturnDocument(option.After),
)

代码我don't想要有

var noteUpdate models.NoteUpdate
ctx.BindJSON(&noteUpdate)
//omit validation and errors handling
bsonNote := bson.NewDocument()
if noteUpdate.Title != "" {
    bsonNote.Append(bson.EC.String("title", noteUpdate.Title))
}
if noteUpdate.Content != "" {
    bsonNote.Append(bson.EC.String("content", noteUpdate.Content))
}
//..setting the rest of the fields...
res := collection.FindOneAndUpdate(
    context.Background(),
    bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)),
    bson.NewDocument(bson.EC.SubDocument("$set", bsonNote)),
    findopt.OptReturnDocument(option.After),
)

所以,确切的问题是 - 有没有办法动态构建 *bson.Documentbson标签(没有像我的 SetWrapper 这样的预定义包装器)?


不幸的是,目前不支持此功能。

您可以创建一个辅助函数,将结构值“转换”为bson.D https://pkg.go.dev/github.com/mongodb/mongo-go-driver/bson#D像这样:

func toDoc(v interface{}) (doc *bson.D, err error) {
    data, err := bson.Marshal(v)
    if err != nil {
        return
    }

    err = bson.Unmarshal(data, &doc)
    return
}

然后可以像这样使用:

partialUpdate := &NoteUpdate{
    Title: "Some new title",
}

doc, err := toDoc(partialUpdate)
// check error

res := c.FindOneAndUpdate(
    context.Background(),
    bson.NewDocument(bson.EC.String("_id", "some-note-id")),
    bson.NewDocument(bson.EC.SubDocument("$set", doc)),
)

希望ElementConstructor.Interface() https://godoc.org/github.com/mongodb/mongo-go-driver/bson#ElementConstructor.Interface将来会改进并允许直接传递结构值或指向结构值的指针。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

mongodb-go-driver/bson 结构到 bson.Document 编码 的相关文章

  • 我想在后端验证来自 golang 前端的时区

    前端在注册期间发送时区以及其他用户详细信息 我需要在时区上放置一个验证器来进行 api 测试 时区数据的格式为 GMT 10 00 Hawaii GMT 08 00 Pacific Time US amp Canada 我所做的是定义数组中
  • MongoDB 如何使用 $date 运算符进行查询?

    编辑 上下文 我正在使用 Talend ETL 工具 并在查询中使用 ISODate 或 Date 或 new Date 如下所示失败并出现错误 因此我需要解决方法 dt ISODate 2014 01 01 dt Date 2014 01
  • 显示来自 mongodb 的所有数据并在 doT.js 模板引擎中渲染它

    我想从 mongodb 中提取数据并将其传递给视图 一切似乎都正常 但我没有看到所有 10000 条记录都显示出来 而是只看到了一条 我觉得我非常接近解决它 但我陷入困境 我正在使用node mongodb native express和d
  • 使用mongoid动态创建索引

    我有一项为我的文档创建新字段的工作 我想在这项工作结束时创建该字段的索引 我试过 Model index field gt 1 and also Mongoid Sessions default rating prediction ensu
  • 使用 Javascript 和 Mongodb 对时间序列数据重新采样

    时间序列数据的数据集需要从具有不规则时间间隔的数据集转换为规则时间序列 可能使用插值和重采样 蟒蛇的pandas Dataframe resample http pandas pydata org pandas docs stable ge
  • $lookup结果中的$match

    我有下一个蒙戈代码 db users aggregate match and UserName eq administrator Company CompanyName eq test lookup from companies local
  • 如何在 MongoDB v3.0.5 中创建用户

    我需要在 mongodb 中为我的数据库创建一个用户 但似乎我无法让它工作 我已经在我的 Windows 7 机器上安装了 mongoDb v3 0 5 根据本文 https docs mongodb org v3 0 tutorial a
  • GAE Go — 如何对不存在的实体键使用 GetMulti?

    我发现自己需要做一个GetMulti使用键数组进行操作 其中某些实体存在 但有些实体不存在 我当前的代码 如下 返回错误 datastore no such entity err datastore GetMulti c keys info
  • 如何在 Go 中解组具有多个项目的简单 xml?

    我想从以下 xml 中获取人物 People 的一部分
  • GOPATH值设置

    我用go1 3 1 windows amd64 msi安装go 安装后GOROOT是默认设置 我发现 D Programs Go bin 在 PATH 中 然后我创建一个 GOPATH 环境变量 使用 go get 命令时 出现错误 软件包
  • 当字段不为空时创建部分索引

    我正在尝试在字段上创建部分索引 但仅当该字段不为空时 换句话说 我希望能够让许多文档能够存储 null 但对于在字段中实际具有值的文档 我希望该值是唯一的 这是我尝试使用的代码 db account createIndex email 1
  • 在 MongoDb 上序列化仅获取属性

    使用 C 6 我可以写 public class Person public Guid Id get public string Name get public Person Guid id string name Id id Name n
  • Spring Data MongoDB 和批量更新

    我正在使用 Spring Data MongoDB 并且想要执行批量更新 就像此处描述的那样 http docs mongodb org manual reference method Bulk find update Bulk find
  • 更新插入 MongoDB 时如何防止出现“_t”字段?

    我有一个应用程序 它使用 MongoDB 的 C 驱动程序将 Upsert 插入 MongoDB 数据库 当我打电话给Update函数 我无法指定我要更新的类型 然后 t字段插入元素的类型 这是我用来更新插入的代码 collection U
  • mongorestore 从独立到复制集

    我已转储在默认端口上运行的独立 mongo 数据库 14Gb 大 如下所示 mongodump username
  • 如何在特定文件夹中运行 shell 命令

    我可以用这个out err exec Command git log Output 获取将在与可执行位置相同的路径中运行的命令的输出 如何指定要在哪个文件夹中运行命令 exec Command https golang org pkg os
  • Golang 正则表达式命名组和子匹配

    我正在尝试匹配正则表达式并获取匹配的捕获组名称 当正则表达式仅与字符串匹配一次时 这是有效的 但如果它与字符串匹配多次 SubexpNames不返回重复的名称 这是一个例子 package main import fmt regexp fu
  • Golang GAE - 小胡子结构中的 intID

    这是一个Example https www dropbox com sh ur2ws1jnik6euef PjVJSwDTUc Blog Golang zip该应用程序的 关键代码在 golang code handler handler
  • PHP 致命错误:未找到“MongoClient”类

    我有一个使用 Apache 的网站 代码如下 当我尝试访问它时 我在 error log 中收到错误 PHP Fatal Error Class MongoClient not found 以下是可能错误的设置 但我认为没有错误 php i
  • 这两种方式哪一种是惯用的方式? time.Sleep() 还是自动收报机?

    我必须每分钟执行一些语句 我不确定我应该遵循以下哪一项 如果有人能解释内存和 CPU 方面的优缺点 那就太好了 时间 Sleep func main go func for time Sleep time Minute fmt Printl

随机推荐