Top games that friends often play together

Just stepping into the world of mongodb, my query skills are still a work in progress. Let's dive straight into the problem at hand. Here is an example document for each user:

{
    id:"14198959",
    user_name:"kikStart2X"
    friends:[
                {
                    friend_id:"1419897878",
                    friend_name:"nitpick",
                    profile_picture:"some image data",
                },
                {
                        friend_id:"14198848418",
                        friend_name:"applePie",
                        profile_picture:"some image data",
                }, //etc
            ],
    games:[
            {
                game_id:"1" , 
                game_name:"Bunny Hop"
            },
            {
               game_id:"2" , 
               game_name:"Racing cars",
            },
          ],
}

Now, all the documents in the collection follow the same structure.

1) The friends array represents the users who are my friends.

2) The games array represents the games I have played.

Each of my friends would have a similar document structure with their own list of games they have played.

What I am aiming for is to identify and list the most common games between me and my friends, in any order specified - ascending, descending or otherwise.

The desired result should appear as follows:

{
    result:
    [
        {
            game_id:"1" , 
            game_name:"Bunny Hop",
            friends:
            [
                {
                        friend_id:"1419897878",
                        friend_name:"nitpick",
                        profile_picture:"some image data",
                },
                {
                        friend_id:"14198848418",
                        friend_name:"applePie",
                        profile_picture:"some image data",
                },

            ]
        },
        {
            game_id:"2" , 
            game_name:"Racing cars",
            friends:
            [
                {
                        friend_id:"71615343",
                        friend_name:"samuel",
                        profile_picture:"some image data",
                },
            ]
        }
    ]
}

This may pose a challenging task, but I lack the knowledge on how to approach it even after hours of scouring the internet for solutions. Thank you in advance to all MongoDB experts out there!

Answer №1

If you're looking to aggregate data, consider the following query.

Start by using the $unwind operation on the friends array, then follow it up with a $lookup for each friend's games.

Next, utilize $unwind on the friendsgames field and compare the common games between the input document's games and each friend's games using $setIntersection in the $project stage.

To complete the process, group the results by games to gather friends who share the same games.

db.collection.aggregate( [
   { $unwind:"$friends" },     
   {
      $lookup: {
         from: collectionname,
         localField: "friends.friend_id",
         foreignField: "id",
         as: "friendsgames"
        }
   },
   { $unwind:"$friendsgames" },
   { $project:{commongames:{$setIntersection:["$games", "$friendsgames.games"]}, friends:1  }},
   { $unwind:"$commongames" },
   { $group:{_id:"$commongames", friends:{$push:"$friends"} } }    
] )

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

Step-by-step guide on implementing a fade effect to a specific JavaScript element ID

When I click a button, the image on the screen disappears. I am looking to add a fade effect to this action. Can someone help me achieve this using CSS? #hide{-webkit-transition: all 1s ease-in-out;} For reference, here is a demo showcasing the current b ...

Increase the width in a leftward direction

I am looking to increase the width from right to left. <div dir="rtl" id="progress"> <dt id='dt'></dt> <dd id='dd'></dd> </div> The ultimate objective here is to have this progress bar progr ...

Testing a Vue component that includes a Vuetify data table with customized slots

I have been struggling to write a Jest test for a simple component that includes a nested v-data-table component. While the page renders correctly in the browser, my test keeps failing. The problem seems to lie with the template I am using for the slot - ...

Removing a parameter from a variable in jQuery and JavaScript

I have coded something and assigned it to a variable. I now want to replace that value with another one. Just so you know, I do most of my coding in perl. Specifically, I am looking to remove the menu_mode value. Any advice on this would be greatly appre ...

``There seems to be an issue with the toLocaleString function not properly formatting the

I have been tasked with writing a function that follows specific instructions, but for some reason, it is not working as expected. Here are the guidelines: Utilize the .toLocaleString function on both the amount and buyerCountry to format the amount into ...

What is the best way to alert a user before they navigate away from a page with content in a textarea?

I am attempting to recreate the functionality seen on textareas in Stack Overflow. UPDATE: Following the advice provided here, I have implemented something similar to the following: window.onbeforeunload = function() { var myTextArea = document.getE ...

Updating button appearance when clicked using Vue.js and Tailwind CSS

As part of my learning journey, I have expanded this code to enhance my frontend skills. While I am aware that the code can be significantly shortened, I am focused on learning and broadening my experience in frontend development. The code below functions ...

Troubleshooting Promise resolution issue within TestBed.compileComponents in Angular 2 testing

I'm currently in the process of developing a test module for a module within my Angular2 component that utilizes the templateUrl property. As a result, I need to make the TestBed.compileComponents async call to compile before conducting any testing. ...

An unfamiliar data type is provided as a number but is treated as a string that behaves like a number

Here is the code snippet in question: let myVar = unknown; myVar = 5; console.log((myVar as string) + 5); Upon running this code, it surprisingly outputs 10 instead of what I expected to be 55. Can someone help me understand why? ...

Issue with React's handleChange function in two separate components

I need assistance with calling the event handleChange from a second Component This is my principal component: const [mainState, setMainState] = useState({ stepValue: 1, saleDateVal: new Date(), customerVal: '' }); function moveNextStep() { ...

Is there potentially a memory leak in this code? If there is, what steps can be taken to eliminate it?

Recently I inherited a project from my senior colleagues that focused on seamless page reloading using AJAX. The code is filled with numerous functions like this one: function iCreateProblems() { //some random code document.getElement ...

Issue with repeated items in Flatlist

Whenever I display my flatlist, it appears to be duplicating the items within it (the feedCache has only one index but the data for this index is rendered twice). Below is the code snippet for the flatlist: const FeedBody = React.memo(() => { return ...

Unable to reach the object property while using the $.each method

Upon receiving an object from an ajax request, I am using $.each to iterate through all the appointments in the object. However, I am encountering an issue where the object appears to be undefined within the $.each loop. Here is the code snippet for my req ...

How can elements with class prefix names be retrieved in IE Browser Helper Object using c#?

I've been developing an IE Plugin using BHO and I need to access an element based on its class prefix in C#. In JavaScript and jQuery, I was able to accomplish this with the following code: var myClass = $('[class^="ii gt"]'); and var myC ...

Is it possible to call time by reference with two levels of referencing?

Issue Description I am facing a challenge in modifying a referenced variable with two levels up in PHP without encountering the error message: Deprecated: Call-time pass-by-reference has been deprecated My Investigation In my search for solutions, I hav ...

Keep duplicating a single object until it fills up the entire screen

Is there a way to make an HTML/CSS element repeat until it covers the entire screen height, without repeating it indefinitely? #container{ height: 100vh; width: 100vw; } .dotts{ background-color: yellow; border-radius: 50%; height: 20px; width: 20p ...

Sending a JSON object containing quotes, URLs, and other data through a POST request in Javascript

I have been researching how to convert JavaScript to JSON and properly escape characters, but I am not having much luck. I need to pass a large JavaScript object in a POST call using Postman, following this structure: { "key":"/url/url/es", "value":"{myDa ...

Vue components fail to display properly when transitioning between routes in Vue (version 3) using the Vue Router

Just diving into VueJS version 3 and vue-router. Despite my efforts to troubleshoot by consulting Stack Overflow and Google, the issue remains unresolved. I have defined two routes: /login /admin/index The Problem: While the login route ...

What is the best way to effectively utilize bootstrap and JavaScript together?

I've been trying to implement some JavaScript on top of Bootstrap 5, but it doesn't seem to be working. I'm not sure if I'm doing something wrong with the JavaScript itself, or if there's an issue with how it's interacting wit ...

Stripe: Either a source or customer must be provided

I've been working on incorporating Stripe into my online shopping cart project, but I've hit a roadblock. Whenever I try to submit the checkout form, I keep encountering the error message: "Must provide source or customer." I suspect there might ...