Home >Backend Development >Golang >How to Retrieve Item Count Based on Multiple Attribute Values in MongoDB using Aggregation Pipeline?
Retrieve Item List by Checking Multiple Attribute Values in MongoDB
When working with MongoDB, it often becomes necessary to retrieve specific items based on multiple attribute values, similar to the IN condition used in MySQL. This article demonstrates how to achieve this using a combination of pipeline operations in MongoDB.
Aggregation Framework
In this scenario, we'll use the aggregation framework to construct a pipeline that filters and aggregates data from a MongoDB collection known as "venueList." The goal is to retrieve the total count of users with specific operating systems, such as Linux or Ubuntu, based on a list of venue IDs.
Pipeline Stages
The pipeline consists of several stages that work together to transform and summarize the data:
Expected Output
The final output of the aggregation pipeline will be a document containing the total count of Linux and Ubuntu users across the specified venue IDs:
<code class="json">{ "_id": null, "linux": 14, "ubuntu": 4 }</code>
Go Implementation
To use this pipeline in Go using the mgo package, you can follow these steps:
<code class="go">query := []bson.M{ {"$match": bson.M{"venueList.id": bson.M{"$in": []string{"VID1212", "VID4343"}}}}, {"$unwind": "$venueList"}, {"$match": bson.M{"venueList.id": bson.M{"$in": []string{"VID1212", "VID4343"}}}}, {"$unwind": "$venueList.sum"}, { "$group": bson.M{ "_id": nil, "linux": bson.M{"$sum": bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$venueList.sum.name", "linux"}}, "$venueList.sum.value", 0}}}, "ubuntu": bson.M{"$sum": bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$venueList.sum.name", "ubuntu"}}, "$venueList.sum.value", 0}}}, }, }, }</code>
The above is the detailed content of How to Retrieve Item Count Based on Multiple Attribute Values in MongoDB using Aggregation Pipeline?. For more information, please follow other related articles on the PHP Chinese website!