How can I Retrieve the Count of All Linux Users by Selecting Specific Venue IDs in MongoDB using Go?

Linda Hamilton
Release: 2024-10-26 02:27:02
Original
549 people have browsed it

How can I Retrieve the Count of All Linux Users by Selecting Specific Venue IDs in MongoDB using Go?

Retrieve Item List by Checking Multiple Attribute Values in MongoDB in Go

Problem:

Retrieve selected items by identifying multiple conditions in MongoDB, analogous to the IN condition in MySQL:

<code class="sql">SELECT * FROM venuelist WHERE venueid IN (venueid1, venueid2)</code>
Copy after login

Consider the JSON structure:

<code class="json">{
  "_id" : ObjectId("57f940c4932a00aba387b0b0"),
  "tenantID" : 1,
  "date" : "2016-10-09 00:23:56",
  "venueList" : [
    {
      "id" : "VID1212",
      "sum" : [
        {
          "name" : "linux",
          "value" : 12
        },
        {
          "name" : "ubuntu",
          "value" : 4
        }
      ],
      "ssidList" : [
        {
          "id" : "SSID1212",
          "sum" : [
            {
              "name" : "linux",
              "value" : 8
            },
            {
              "name" : "ubuntu",
              "value" : 6
            }
          ],
          "macList" : [
            {
              "id" : "12:12:12:12:12:12",
              "sum" : [
                {
                  "name" : "linux",
                  "value" : 12
                },
                {
                  "name" : "ubuntu",
                  "value" : 1
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "id" : "VID4343",
      "sum" : [
        {
          "name" : "linux",
          "value" : 2
        }
      ],
      "ssidList" : [
        {
          "id" : "SSID4343",
          "sum" : [
            {
              "name" : "linux",
              "value" : 2
            }
          ],
          "macList" : [
            {
              "id" : "43:43:43:43:43:34",
              "sum" : [
                {
                  "name" : "linux",
                  "value" : 2
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}</code>
Copy after login

Task: Retrieve the count of all Linux users by selecting venue IDs 'VID1212' and 'VID4343'.

Solution:

  1. Use the aggregation framework to filter documents based on venueList IDs using $match.
  2. Unwind venueList and sum subdocument arrays using $unwind.
  3. Filter again using $match for desired IDs.
  4. Use $group** to aggregate filtered documents, using **$sum accumulator for desired values.
  5. Condition using a ternary operator ($cond) to create independent count fields.
<code class="go">// Import the necessary packages.
import (
    "context"
    "fmt"

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

// retrieveItemListByAttributeValues retrieves items based on multiple attribute values in MongoDB.
func retrieveItemListByAttributeValues(client *mongo.Client) {
    // Create a new context.
    ctx := context.Background()

    // Define the pipeline.
    pipeline := mongo.Pipeline{
        {{"$match", bson.D{{"venueList.id", bson.D{{"$in", bson.A{"VID1212", "VID4343"}}}}}}},
        {{"$unwind", "$venueList"}},
        {{"$match", bson.D{{"venueList.id", bson.D{{"$in", bson.A{"VID1212", "VID4343"}}}}}}},
        {{"$unwind", "$venueList.sum"}},
        {
            {"$group", bson.D{
                {"_id", nil},
                {"linux", bson.D{{"$sum", bson.M{"$cond", bson.A{bson.VC.Bool(true), "$venueList.sum.value", 0}}}}}},
                {"ubuntu", bson.D{{"$sum", bson.M{"$cond", bson.A{bson.VC.Bool(true), "$venueList.sum.value", 0}}}}}},
            }},
        },
    }

    // Execute the aggregation pipeline.
    aggRes, err := client.Database("test").Collection("venuelist").Aggregate(ctx, pipeline)
    if err != nil {
        panic(err)
    }

    // Iterate over the results.
    for aggRes.Next(ctx) {
        var result bson.M
        if err := aggRes.Decode(&result); err != nil {
            panic(err)
        }

        // Print the result.
        fmt.Println(result)
    }

    // Close the cursor.
    if err := aggRes.Close(ctx); err != nil {
        panic(err)
    }
}</code>
Copy after login

Alternative Solution:

For improved performance and flexibility, consider the following alternative pipeline:

<code class="go">pipeline := mongo.Pipeline{
    {{"$match", bson.D{{"venueList.id", bson.D{{"$in", bson.A{"VID1212", "VID4343"}}}}}}},
    {{"$unwind", "$venueList"}},
    {{"$match", bson.D{{"venueList.id", bson.D{{"$in", bson.A{"VID1212", "VID4343"}}}}}}},
    {{"$unwind", "$venueList.sum"}},
    {
        {"$group", bson.D{
            {"_id", "$venueList.sum.name"},
            {"count", bson.D{{"$sum", "$venueList.sum.value"}}},
        }},
    },
    {
        {"$group", bson.D{
            {"_id", nil},
            {"counts", bson.D{{"$push", bson.D{
                {"name", "$_id"},
                {"count", "$count"},
            }}}},
        }},
    },
}</code>
Copy after login

The above is the detailed content of How can I Retrieve the Count of All Linux Users by Selecting Specific Venue IDs in MongoDB using Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!