Home > Backend Development > Golang > How to Efficiently Count User Agent Occurrences Across Multiple Venues in MongoDB Using Go?

How to Efficiently Count User Agent Occurrences Across Multiple Venues in MongoDB Using Go?

Susan Sarandon
Release: 2024-10-26 11:00:02
Original
222 people have browsed it

How to Efficiently Count User Agent Occurrences Across Multiple Venues in MongoDB Using Go?

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

The goal is to retrieve a list of items in MongoDB by matching multiple attribute values, similar to the IN condition in SQL. In this case, the objective is to count the occurrences of "linux" and "ubuntu" user agents in a JSON document that contains an array of venue lists. Each venue list has an array of sum subdocuments, which contain the user agent names and values.

The solution involves using the aggregation framework in MongoDB and the mgo package in Go. Here's a breakdown of the aggregation pipeline:

  1. Filter by Venue ID: Use the $match pipeline to select documents where the venueList.id field matches the desired venue IDs (e.g., "VID1212" and "VID4343").
  2. Unwind Venue List: Use the $unwind pipeline to denormalize the venueList array, creating separate documents for each venue.
  3. Filter Venue ID: After unwinding, filter the documents again to ensure that only the desired venue IDs remain.
  4. Unwind Sum Subdocument: Unwind the sum subdocument array to denormalize the user agent names and values.
  5. Group and Sum: Use the $group pipeline to group the documents by user agent name, and sum the corresponding values using the $sum operator.
  6. Create Independent Count Fields: For readability, you can use ternary operators ($cond) within the $group pipeline to create independent count fields for "linux" and "ubuntu."
  7. Alternative Approach for Better Performance: For a more efficient alternative, you can use a slightly different $group pipeline to aggregate the user agent counts and group them by name.

Finally, convert the aggregation pipeline to Go using the mgo.Collection.Pipe() method to execute it against the MongoDB collection. This will return a list of items with their associated counts for the specified user agents and venue IDs.

The above is the detailed content of How to Efficiently Count User Agent Occurrences 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