在 Go 中通过检查 MongoDB 中的多个属性值来检索项目列表
在 MongoDB 中,可以使用以下方式实现基于多个属性值检索项目聚合管道。这是使用 mgo.v2 包的 Go 实现:
<code class="go">import ( "context" "fmt" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) func RetrieveItemListByMultipleAttributeValues(databaseName, collectionName string, venueIDs []string) (map[string]int, error) { ctx := context.Background() // Create a new MongoDB connection. session, err := mgo.Dial("mongodb://host:port") if err != nil { return nil, fmt.Errorf("Error dialing MongoDB: %w", err) } defer session.Close() // Select the database and collection. collection := session.DB(databaseName).C(collectionName) // Define the aggregation pipeline. pipeline := []bson.M{ {"$match": bson.M{"venueList.id": bson.M{"$in": venueIDs}}}, {"$unwind": "$venueList"}, {"$match": bson.M{"venueList.id": bson.M{"$in": venueIDs}}}, {"$unwind": "$venueList.sum"}, {"$group": bson.M{ "_id": "$venueList.sum.name", "count": bson.M{"$sum": "$venueList.sum.value"}, }}, {"$group": bson.M{ "_id": nil, "counts": bson.M{ "$push": bson.M{ "name": "$_id", "count": "$count", }, }, }}, } // Run the aggregation pipeline. resultIterator, err := collection.Pipe(pipeline).Iter() if err != nil { return nil, fmt.Errorf("Error running aggregation pipeline: %w", err) } // Create a map to store the aggregated results. result := make(map[string]int) // Decode each result and add it to the map. for resultIterator.Next(&result) { for _, count := range result["counts"].([]interface{}) { result[count.(map[string]interface{})["name"].(string)] = count.(map[string]interface{})["count"].(int) } } // Close the result iterator. resultIterator.Close() // Return the result map. return result, nil }</code>
以上是如何使用 Go 在 MongoDB 中基于多个属性值检索项目?的详细内容。更多信息请关注PHP中文网其他相关文章!

本文解释了GO的软件包导入机制:命名imports(例如导入“ fmt”)和空白导入(例如导入_ fmt; fmt;)。 命名导入使包装内容可访问,而空白导入仅执行t

本文解释了Beego的NewFlash()函数,用于Web应用程序中的页间数据传输。 它专注于使用newflash()在控制器之间显示临时消息(成功,错误,警告),并利用会话机制。 Lima

本文详细介绍了MySQL查询结果的有效转换为GO结构切片。 它强调使用数据库/SQL的扫描方法来最佳性能,避免手动解析。 使用DB标签和Robus的结构现场映射的最佳实践

本文演示了创建模拟和存根进行单元测试。 它强调使用接口,提供模拟实现的示例,并讨论最佳实践,例如保持模拟集中并使用断言库。 文章

本文探讨了GO的仿制药自定义类型约束。 它详细介绍了界面如何定义通用功能的最低类型要求,从而改善了类型的安全性和代码可重复使用性。 本文还讨论了局限性和最佳实践

本文详细介绍了在GO中详细介绍有效的文件,将OS.WriteFile(适用于小文件)与OS.openfile和缓冲写入(最佳大型文件)进行比较。 它强调了使用延迟并检查特定错误的可靠错误处理。

本文使用跟踪工具探讨了GO应用程序执行流。 它讨论了手册和自动仪器技术,比较诸如Jaeger,Zipkin和Opentelemetry之类的工具,并突出显示有效的数据可视化


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)