How to Efficiently Count Specific Attributes Across Multiple Venues in MongoDB using Go?

Mary-Kate Olsen
Release: 2024-10-25 21:57:03
Original
559 people have browsed it

How to Efficiently Count Specific Attributes Across Multiple Venues in MongoDB using Go?

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

Problem:

Given a JSON data structure with a nested list of venues and their attributes, how do you retrieve the count of specific attributes (e.g., linux users) for multiple venues? For instance, you want to count the number of linux users for venues with IDs 'VID1212' and 'VID4343'.

Solution:

To achieve this in MongoDB, you can utilize the aggregation framework:

  1. $match: Filter documents based on the specified venue IDs using the $in operator.
  2. $unwind: Flatten the nested venueList and sum arrays to denormalize the data.
  3. $match (second application): Re-filter the unwound documents to consider only the desired venue IDs.
  4. $unwind (second application): Continue unwinding nested sum subdocuments.
  5. $group:** Group the documents based on the **name** field of the sum subdocument and aggregate the **value** field using the accumulator **$sum.
  6. $cond: Use a conditional expression to create separate count fields for each desired attribute (e.g., linux, ubuntu).

For a more flexible alternative:

  1. Replace the last aggregation stage with:

    { 
     "$group": {
         "_id": null,
         "counts": {
             "$push": {
                 "name": "$_id",
                 "count": "$count"
             }
         }
     }
    }
    Copy after login

This alternative groups based on the attribute name and pushes the corresponding count into an array.

For implementation in Golang using mGo (v2), refer to the guidance on http://godoc.org/labix.org/v2/mgo#Collection.Pipe.

The above is the detailed content of How to Efficiently Count Specific Attributes Across Multiple Venues 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