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      
    }
    
  • 相关阅读:
    手势识别 ios
    无题
    核心动画笔记
    Quartz2D的学习2
    Quartz2D的学习1
    NSURLsessionTask
    NSURLSession
    POST请求的两种方式
    网络第一天
    NSThread
  • 原文地址:https://www.cnblogs.com/flipped/p/13435521.html
Copyright © 2011-2022 走看看