使用 golang 的 MongoDB upsert 数组文档

标签 mongodb go

我有一个如下文件:

 {
       "_id": "1.0",
        files: [
          {"name": "file_1", "size": 1024, "create_ts": 1570862776426},
          {"name": "file_2", "size": 2048, "create_ts": 1570862778426}
        ]
    }

我想用“file_x”插入"file":
1 如果“file_x”已经在“files”中,则更新,例如“file_x”为:
{"name": "file_2", "size": 4096, "create_ts": 1570862779426}

upsert文件后是:
{
   "_id": "1.0",
    files: [
      {"name": "file_1", "size": 1024, "create_ts": 1570862776426},
      {"name": "file_2", "size": 4096, "create_ts": 1570862779426}}
    ]
}

2 如果“file_x”不在“files”中,则插入,例如“file_x”为:
{"name": "file_3", "size": 4096, "create_ts": 1570862779426}

在 upsert 文件之后是:
{
   "_id": "1.0",
    files: [
      {"name": "file_1", "size": 1024, "create_ts": 1570862776426},
      {"name": "file_2", "size": 2048, "create_ts": 1570862778426},
      {"name": "file_3", "size": 4096, "create_ts": 1570862779426}
    ]
}

那么我可以使用一个功能来存档它吗?

最佳答案

您将需要手动执行此操作。文档中的嵌入式结构没有 upsert 机制。

首先获取文档,检查是否file_x在文件列表中,如果没有,插入它。然后将文档保存回来。

您应该确保在任何给定时间,只有一个程序/goroutine 正在尝试执行此操作,否则您将遇到竞争条件和 file_x可能会被多次插入。

关于使用 golang 的 MongoDB upsert 数组文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58353030/

相关文章:

node.js - 如何在 Mongo 中为数组的元素定义唯一索引

go - 开始-指向 bool * bool的指针的合理性是什么?

performance - Go 中异步 TCP 服务器的正确结构是什么?

go - 查找高于均值的数字

html - Go Lang - 在目录结构中的什么地方放置用于 HTML 模板的图像?

mongodb - 如何在 Meteor 发布函数中使用 rawCollection

javascript - MongoDB 聚合框架 - 如何查询平均值

go - Golang中的Web应用程序供离线/浏览器使用

javascript - Mongoose 不创建索引

node.js - 使用 mongoose 检查 mongodb 中是否存在文档