Exploring MongoDB: determining the frequency of shared values among a group of documents

I have a dataset with two fields and I am looking to determine the count of common values within the same category of rows:

The current data is represented in JSON format like this:

https://i.sstatic.net/LIToV.png

I am seeking an output similar to this:

https://i.sstatic.net/YQNGH.png

Any assistance or advice on how to achieve this would be greatly appreciated. Thank you.

Answer №1

To start, organize your data into an array of objects. Then, employ the subsequent algorithm to extract the desired information:

  1. Determine the unique categories
    ["Music", "Film", "History", "Science"]
  2. Generate combinations from those categories
    [["Music", "Film"], ["Music", "History"], ["Music", "Science"], ["Film", "History"], ...]
  3. Establish a mapping of category names to the books they contain using a Set for uniqueness. The map will follow this structure: "
    {"Music": Set("A", "B"), "Film": Set("A", "B", "C"), "History": Set("C", "B"), "Science": Set("C")}
    "
  4. Utilize the previously created objects and arrays to identify duplicates within the combinations.
  5. After completion, you'll have an array structured as follows:
    [ [cat1, cat2, [bookInCommon1, bookInCommon2]], [cat1, cat3, [bookInCommon1, bookInCommon2]], ...]

Execute the code below to witness it in action. mongoData stores the data fetched from MongoDB.

const mongoData = [{ 
    category: "Music",
    book: "A"
}, {
    category: "Music",
    book: "B"
},{  
    ...
}];

// Steps outlined above
...

combos.forEach(combo => { 
    console.log("Combo: " + combo[0] + ", " + combo[1]);
    console.log("\tNumber of dupes: " + combo[2].length); 
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The toArray function in MongoDB does not support the use of Array push

I'm attempting to loop through all documents within collections, store them in a global variable, but it seems like the push() function is not working and returning an empty array [] inside of toArray(). Any ideas? const mongo = require('mongodb ...

Retrieve objects from an array in MongoDb based on a specific condition within the object property

Currently, I'm exploring the world of mongoose and nodejs, attempting to create a server-side script quickly in nodejs. My main goal is to fetch data as an array of objects from mongoDb using mongoose. Below is a glimpse of my Schema: var heatmapSch ...

Is there a way to prevent Highcharts from automatically rounding decimal values to zero?

The ecpm values ["0.4", "0.2", "0.6", "0.3"] are being passed as data for the y-axis to draw a spline on a multi-axis graph using Highcharts. However, instead of showing the correct values, the spline is appearing as a straight horizontal line with the val ...

Rotation to a point in a circle using three.js

Currently, I am in possession of 2 instances of THREE.Vector3(). My task at hand is to create a circular shape around one vector with the second vector serving as a tangent. I have determined the radius of the circle geometry based on the distance betwee ...

Is it possible to resolve the error message "Uncaught TypeError: Cannot read property 'node' of undefined" when utilizing d3-tip with npm?

After installing d3": "^3.5.17" and "d3-tip": "^0.7.1" via npm (d3-tip documentation), the following code was added to my index.js file: var d3 = require('d3'); var d3tip = require('d3-tip')(d3); console.log('d3 version', d3. ...

Node timers exhibiting unexpected behavior contrary to documented specifications

Feeling a bit lost with this one. I'm running Ubuntu and using nvm for node. I made sure to uninstall the version of node installed via apt just to be safe. node --version > v10.10.0 npm --version > 6.4.1 So, I go ahead and create-react-app a ...

Querying a record in MongoDB with the "$" selector is not possible

Encountering a strange issue when working with NodeJS and Mongoose for querying records in MongoDB. I have defined my Product model as follows: const mongoose = require("mongoose"); const productSchema = new mongoose.Schema({ name: String, b ...

Node.JS - Struggling to successfully export environment variables between scripts in package.json

Currently, I am working on a Node.JS project using Express and I am facing an issue while setting up environment variables to differentiate between development and production environments. I have created a shell script file containing some environment vari ...

JavaScript - The AJAX response is consistently after being undefined

I am encountering an issue with the following functions: function get_non_authorized_bulk_edit_option_values() { var modificable_column_names = get_write_user_values(); alert(modificable_column_names); } The above function is calling this ...

What could be the reason my Backbone view is failing to render?

Can anyone help me troubleshoot why this template isn't rendering properly in my backbone views? Any insights would be greatly appreciated! Below, I've included the code from my jade file for the views and the main.js file for the backbone js scr ...

What is the best way to add elements to a custom-defined array?

I am currently utilizing Angular 5 with typescript version 2.7.1. Within typescript, I have created a custom type: arr: {id: string; name: string; }[]; I am attempting to add an element to the array and have experimented with the following methods: thi ...

Page experiencing issues with JavaScript functionality

Here is a simple function that I am using to shake a form when the user's email is not valid: function shakeForm() { var l = 10; for( var i = 0; i < 10; i++ ) $("form").animate( { 'margin-left': "+=" + ( l = -l ) + 'px ...

Traverse Through multiple strings in double pointer of characters

Looking at a function with the signature below: void foo (char **bar); The 'bar' variable represents an array of strings without a specified length. I am faced with the challenge of writing a loop to check if each string in 'bar' mee ...

Managing the "Accept Cookies" notification using Selenium in JavaScript

As I use Selenium to log in and send messages on a specific website, I am faced with a cookie popup that appears each time. Unfortunately, clicking the accept button to proceed seems to be quite challenging for me. Here is an image of the cookie popup Th ...

Launch current screen inside a jquery dialog box

When attempting to open an existing aspx page within a jQuery dialog, I noticed that the CSS of the parent screen is being overridden by the dialog box. Is there a way to prevent this without making changes to the existing screen? If there are any altern ...

Executing AJAX calls within a forEach loop

I'm facing a challenge with a function that carries out a foreach loop on a list of views and needs to make an AJAX request for each view within the loop. Upon receiving the results in the success callback, it checks if a specific ID is returned and, ...

What is the process for invoking a NodeJS script within a personalized VSCode Extension?

Recently, I created a NodeJS script for one of my projects and now I'm looking to develop a VSCode extension around it. How can I integrate this script as a command within my custom extension? The goal is to have the script packaged along with the e ...

Setting up a textarea tooltip using highlighter.js

I'm experimenting with using highlighter.js within a textarea. I've customized their sample by substituting the p with a textarea enclosed in a pre tag (for right-to-left language settings). <div class="article" style="width: 80%; height: 80% ...

How to use the filter() method to filter an array of objects based on a nested array within each object

The following data presents a list of products along with their inventory information: const data = [ { id: 1, title: "Product Red", inventoryItem: { inventoryLevels: { edges: [{ node: { location: { name: "Warehou ...

A guide to retrieving all image URLs when a checkbox is selected using Javascript

My goal is to extract only image URLs from the concatenated values of price and picture URL. However, when I check different images using checkboxes, it always displays the URL of the first selected image. When I try to split the value, all the prices and ...