【问题标题】:MongoDB upsert array document with golang使用 golang 的 MongoDB upsert 数组文档
【发布时间】:2019-10-13 09:58:10
【问题描述】:

我有如下文件:

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

我想用“file_x”来插入“files”: 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}
    ]
}

那么我可以使用一个函数来归档它吗?

【问题讨论】:

标签: mongodb go


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    在 mongodb 更新语言中没有一个更新操作可以做你想做的事情。您可以使用$addToSet 接近,如果项目不存在,它会添加到一组项目中,但它不会根据字段子集的匹配来更新项目。您最好的选择是在内存写入中执行读取更新。

    【讨论】:

      猜你喜欢
      • 2014-09-14
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      相关资源
      最近更新 更多