目录
问题内容
解决方法
首页 后端开发 Golang 需要帮助从 mongodb 文档获取元素并使用 go mongo 驱动程序更新其值

需要帮助从 mongodb 文档获取元素并使用 go mongo 驱动程序更新其值

Feb 09, 2024 pm 04:09 PM

需要帮助从 mongodb 文档获取元素并使用 go mongo 驱动程序更新其值

php小编草莓在这里为大家介绍一种常见的需求:如何从MongoDB文档中获取元素并使用Go Mongo驱动程序更新其值。MongoDB是一种流行的NoSQL数据库,而Go是一种强大的编程语言,两者的结合可以带来很多好处。在本文中,我们将探讨如何使用Go Mongo驱动程序来实现这个需求,帮助您更好地理解和应用这个技术。

问题内容

嘿,我正在使用 go.mongodb.org/mongo-driver 包来使用 golang。这是我的代码:

package src

import (
    "context"
    "fmt"
    "log"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

var (
    client      *mongo.client
    stickerscol *mongo.collection
)

func init() {
    log.println("setting up database...")
    var err error
    client, err = mongo.connect(context.background(), options.client().applyuri(envars.dburl))
    if err != nil {
        log.fatal(err)
    }
    log.println("connected to database")
    stickerscol = client.database("stickersbot").collection("stickers")
    chatcol = client.database("stickersbot").collection("chat")
}

func changedefaultpack(userid int64, stickername string, format string) error {
    fmt.println(userid, stickername, format)
    filter := bson.m{
        "_id":                      userid,
        "stickers.stickername":     stickername,
        "stickers.stickerpacktype": format,
    }
    updateother := bson.m{
        "$set": bson.m{
            "stickers.$[elem].isdefault": false,
        },
    }
    update := bson.m{
        "$set": bson.m{
            "stickers.$.isdefault": true,
        },
    }
    arrayfilters := options.arrayfilters{
        filters: []interface{}{bson.m{"elem.stickerpacktype": format}},
    }
    updateoptions := options.update().setarrayfilters(arrayfilters)
    _, err := stickerscol.updatemany(context.todo(), filter, updateother, updateoptions)
    if err != nil {
        return err
    }
    ok, err := stickerscol.updateone(context.background(), filter, update, options.update().setupsert(true))
    if err != nil {
        return err
    }
    if ok.modifiedcount == 0 {
        fmt.println("no document matched")
        return fmt.errorf("no document matched")
    }
    return err
}
登录后复制

这是数据库结构:

...
{
  "_id": 1633375527,
  "stickers": [
    {
      "stickerpacktype": "static",
      "stickername": "gVtOy_1633375527_by_ChadManBot",
      "isdefault": true
    },
    {
      "stickerpacktype": "animated",
      "stickername": "zIjsa_1633375527_by_ChadManBot",
      "isdefault": true
    },
    {
      "stickerpacktype": "video",
      "stickername": "bJBle_1633375527_by_ChadManBot",
      "isdefault": true
    },
    {
      "stickerpacktype": "static",
      "stickername": "iujiw_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "video",
      "stickername": "CHnqb_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "XKJUP_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "animated",
      "stickername": "pCFlC_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "animated",
      "stickername": "jGGgt_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "animated",
      "stickername": "cTxyA_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "animated",
      "stickername": "ZfYXO_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "xJUkA_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "HIvsY_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "WIHFQ_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "OqjtE_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "QNysO_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "OrTsT_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "FzROg_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "QUBcT_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "NsZfM_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "AkxVM_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "Ddvus_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "LXfHV_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "sTaMv_1633375527_by_ChadManBot",
      "isdefault": false
    },
    {
      "stickerpacktype": "static",
      "stickername": "vppgK_1633375527_by_ChadManBot",
      "isdefault": false
    }
  ],
  "stickerpackcount": 2
}
...
登录后复制

我需要我的代码是找到与给定 id 和贴纸类型匹配的贴纸包列表,并将其默认值设置为 false 并将传递给 func 的包的默认值设置为 true

基本上只是将其中一个设置为默认值,将其他设置为非默认值。有人可以解释一下为什么这个函数返回未找到文档吗?

解决方法

当有多个字段匹配时,您应该使用 $elemmatch 运算符。否则,$ 运算符不起作用。请参阅 使用多个字段匹配更新嵌入文档

并且您不需要 updatemany 来更新单个文档中的多个数组元素。请改用 updateone

这是基于您的代码和数据的演示:

package main

import (
    "context"
    "fmt"
    "log"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

var (
    client      *mongo.client
    stickerscol *mongo.collection
)

func init() {
    log.println("setting up database...")
    var err error
    client, err = mongo.connect(context.background(), options.client().applyuri("mongodb://localhost"))
    if err != nil {
        log.fatal(err)
    }
    log.println("connected to database")
    stickerscol = client.database("stickersbot").collection("stickers")
}

func changedefaultpack(userid int64, stickername string, format string) error {
    fmt.println(userid, stickername, format)
    filter := bson.m{
        "_id": userid,
        "stickers": bson.m{
            "$elemmatch": bson.m{
                "stickername":     stickername,
                "stickerpacktype": format,
            },
        },
    }
    updateother := bson.m{
        "$set": bson.m{
            "stickers.$[elem].isdefault": false,
        },
    }
    arrayfilters := options.arrayfilters{
        filters: []interface{}{bson.m{"elem.stickerpacktype": format}},
    }
    updateoptions := options.update().setarrayfilters(arrayfilters)
    result, err := stickerscol.updateone(context.background(), filter, updateother, updateoptions)
    if err != nil {
        return err
    }
    log.printf("update other: %+v\n", result)

    update := bson.m{
        "$set": bson.m{
            "stickers.$.isdefault": true,
        },
    }
    ok, err := stickerscol.updateone(context.background(), filter, update, options.update().setupsert(true))
    if err != nil {
        return err
    }
    log.printf("update default: %+v\n", ok)
    if ok.modifiedcount == 0 {
        fmt.println("no document matched")
        return fmt.errorf("no document matched")
    }
    return err
}

func main() {
    if err := changedefaultpack(1633375527, "ddvus_1633375527_by_chadmanbot", "static"); err != nil {
        panic(err)
    }
}
登录后复制

运行演示,您将观察到文档发生以下更改:

--- before.json 2023-06-27 00:34:32.721978745 +0800
 after.json  2023-06-27 00:34:59.489836137 +0800
@@ -4,7 +4,7 @@
     {
       "stickerpacktype": "static",
       "stickername": "gVtOy_1633375527_by_ChadManBot",
-      "isdefault": true
+      "isdefault": false
     },
     {
       "stickerpacktype": "animated",
@@ -104,7 +104,7 @@
     {
       "stickerpacktype": "static",
       "stickername": "Ddvus_1633375527_by_ChadManBot",
-      "isdefault": false
+      "isdefault": true
     },
     {
       "stickerpacktype": "static",
登录后复制

以上是需要帮助从 mongodb 文档获取元素并使用 go mongo 驱动程序更新其值的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1673
14
CakePHP 教程
1429
52
Laravel 教程
1333
25
PHP教程
1278
29
C# 教程
1257
24
Golang vs. Python:性能和可伸缩性 Golang vs. Python:性能和可伸缩性 Apr 19, 2025 am 12:18 AM

Golang在性能和可扩展性方面优于Python。1)Golang的编译型特性和高效并发模型使其在高并发场景下表现出色。2)Python作为解释型语言,执行速度较慢,但通过工具如Cython可优化性能。

Golang和C:并发与原始速度 Golang和C:并发与原始速度 Apr 21, 2025 am 12:16 AM

Golang在并发性上优于C ,而C 在原始速度上优于Golang。1)Golang通过goroutine和channel实现高效并发,适合处理大量并发任务。2)C 通过编译器优化和标准库,提供接近硬件的高性能,适合需要极致优化的应用。

开始GO:初学者指南 开始GO:初学者指南 Apr 26, 2025 am 12:21 AM

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

Golang vs.C:性能和速度比较 Golang vs.C:性能和速度比较 Apr 21, 2025 am 12:13 AM

Golang适合快速开发和并发场景,C 适用于需要极致性能和低级控制的场景。1)Golang通过垃圾回收和并发机制提升性能,适合高并发Web服务开发。2)C 通过手动内存管理和编译器优化达到极致性能,适用于嵌入式系统开发。

Golang vs. Python:主要差异和相似之处 Golang vs. Python:主要差异和相似之处 Apr 17, 2025 am 12:15 AM

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。 Golang以其并发模型和高效性能着称,Python则以简洁语法和丰富库生态系统着称。

Golang和C:性能的权衡 Golang和C:性能的权衡 Apr 17, 2025 am 12:18 AM

Golang和C 在性能上的差异主要体现在内存管理、编译优化和运行时效率等方面。1)Golang的垃圾回收机制方便但可能影响性能,2)C 的手动内存管理和编译器优化在递归计算中表现更为高效。

表演竞赛:Golang vs.C 表演竞赛:Golang vs.C Apr 16, 2025 am 12:07 AM

Golang和C 在性能竞赛中的表现各有优势:1)Golang适合高并发和快速开发,2)C 提供更高性能和细粒度控制。选择应基于项目需求和团队技术栈。

Golang vs. Python:利弊 Golang vs. Python:利弊 Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

See all articles