zoukankan      html  css  js  c++  java
  • Golang MongoDB Driver 更新符合条件的数组元素的字段

    在 MongoDB 的 Shell 里修改文档里某个符合条件的数组里的值的字段,可以这样:

    db.collection.updateMany(
       { <query conditions> },
       { <update operator>: { "<array>.$[<identifier>]" : value } },
       { arrayFilters: [ { <identifier>: <condition> } ] }
    )
    

    而在 GoLang 中我们需要使用 MongoDB Driver。

    比如有一个 Collection 里每个文档是这样的:

    {
          "name": "..",
          "array": []{
                {
                      "name": "a",
                      "detail": "....",
                },
                {
                      "name": "b",
                      "detail": "....",
                }
          }
    }
    

    我们要修改 name 为 x 的文档里面 array 里 name 为 b 的记录的 detail 信息为"test"。可以这样写:

    filter := bson.M{"name": "x", "array.name": "b"}
    update := bson.M{"array.$[item].detail": "test"}
    arrayFilter := bson.M{"item.name": "b"}
    
    // coll 是 mongo 的 Collection,下面内容不需要修改。
    res := coll.FindOneAndUpdate(context.Background(), 
          filter, 
          bson.M{"$set": update}, 
          options.FindOneAndUpdate().SetArrayFilters(
                options.ArrayFilters{
                      Filters: []interface{}{
                            arrayFilter,
                      },
                },
          ))
    
    if res.Err() != nil {
          // log error      
    }
    
  • 相关阅读:
    继承与多态——动手又动脑
    类与对象--动手又动脑
    Go语言接口
    GO语言结构体
    GO指针
    GO函数
    GO获取随机数
    GO基础
    Go语言的%d,%p,%v等占位符的使用
    GO语言常量和变量
  • 原文地址:https://www.cnblogs.com/flipped/p/13435521.html
Copyright © 2011-2022 走看看