Explore every conceivable pairing of two fields in a Mongo database

I currently have an array of objects stored in my database

[
  {
     price: "1"
     type: "buy",
  },
  {
     price: "2"
     type: "buy",
  },
  {
     price: "3"
     type: "sell"
  },
  {
     price: "4"
     type: "sell"
  }
]

What is the best way to aggregate this data in order to obtain an array of arrays containing all potential combinations (keeping in mind that the price can be any random number)

Filter out items with the highest buy price

and further organize them, so that items with the greatest price difference are positioned at the top

[
  [
      {
         price: "1"
         type: "buy",
      },
      {
         price: "4"
         type: "sell"
      }
  ],
  [
      {
         price: "1"
         type: "buy",
      },
      {
         price: "3"
         type: "sell"
      },
  ],
  [
      {
         price: "2"
         type: "buy",
      },
      {
         price: "4"
         type: "sell"
      }
  ],
  [
      {
         price: "2"
         type: "buy",
      },
      {
         price: "3"
         type: "sell"
      },
  ],
]

Answer №1

Instructions

  • Perform a self-lookup and only match if the IDs are not the same (to avoid pairing the same item with itself)
  • Use mapping to include the parent item in the final result of the join operation (the pair will always consist of the item with the highest price as the first member, which is necessary for later steps)
  • Unwind the pairs to separate them into individual entities
  • Group the pairs together to remove any duplicates (each pair should only appear twice but they are sorted so we can group by them effectively)
  • Determine the price difference between the paired items, sort them in descending order, and then remove this field from the final result

*It's unclear whether all requirements are met, especially regarding the part about "hiding items with the highest buy price" where the highest buy price is "2" yet those items are still included in the results.

Playmongo

coll.aggregate(
[{"$lookup": 
   {"from": "coll",
    "pipeline": 
     [{"$match": {"$expr": {"$ne": ["$$id", "$_id"]}}},
       {"$project": {"_id": 0, "price": 1, "type": 1}}],
    "as": "pairs",
    "let": {"id": "$_id"}}},
 {"$project": 
   {"_id": 0,
    "pairs": 
     {"$map": 
       {"input": "$pairs",
        "in": 
         {"$cond": 
           [{"$gt": ["$$this.price", "$price"]},
             [{"price": "$price", "type": "$type"}, "$$this"],
             ["$$this", {"price": "$price", "type": "$type"}]]}}}}},
 {"$unwind": "$pairs"}, {"$group": {"_id": "$pairs"}},
 {"$project": {"_id": 0, "pair": "$_id"}},
{"$set"": 
   {"priceDifference": 
     {"$abs": 
       {"$subtract": 
         [{"$toDouble": 
             {"$getField": 
               {"field": "price", "input": {"$arrayElemAt": ["$pairs", 0]}}}},
           {"$toDouble": 
             {"$getField": 
               {"field": "price",
                "input": {"$arrayElemAt": ["$pairs", 1]}}}}]}}}},
 {"$sort": {"priceDifference": -1}},
{"$unset": ["priceDifference"]}])

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

Form with multiple duplicate React components

form field image I am trying to figure out how to collect individual form fields separately in order to store them in the database. For example, having three separate input fields for email addresses... ...

Issue with Fancybox and Jquery compatibility

I'm encountering some issues with conflicting Javascripts. One script is responsible for creating a dropdown menu, while another set of scripts enable fancybox functionality. However, having both sets of scripts in the header code results in conflicts ...

Issue with NodeJS SQL Login: Received error (ERR_HTTP_HEADERS_SENT): Headers cannot be set after being sent to the client

Hi there, I am fairly new to working with nodeJS and I have encountered an issue that I suspect lies within the second if statement inside "db.query..." in the code provided below. An error message showing ERR_HTTP_HEADERS_SENT]: Cannot set headers after ...

Utilizing logical operators to assign values to variables in Typescript

export class SearchResult { id: string; constructor(obj?: any) { this.id = obj && obj.id || null; } } Can someone explain to me the meaning of obj && obj.id || null? I'm confused by this syntax. ...

The style property is returned as null by the React Hook useRef

I am currently working on a modal that requires me to access the id property of an HTML element in order to modify its display property. I attempted to achieve this using the useRef Hook, but encountered the following errors. TypeError: Cannot read propert ...

Bootstrap 5 - Zero response for stack traversal

I have recently designed a basic bootstrap 5 template: <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, i ...

Tips for automatically adjusting the options in a select box based on changes to a textbox

I need to dynamically update the options in a select box based on the input provided in a text box. I am using jQuery autocomplete to show suggestions in a list, and once a suggestion is selected, it should populate the text box. Now, I want to show a list ...

Adding a new item to an array in J

What is the optimal approach to insert an element at a specific position in an array using J? I am struggling with passing three arguments to the verb I am trying to create. The basic idea of the code I intend to write goes like this: insert =. dyad : &a ...

Ways to trigger an event or invoke a function after initializing Stripe JS

My checkout page is optimized with the new Stripe Payment Element for fast loading using SSR. However, I am facing an issue where the element sometimes causes the page to reload 2 or more times before functioning properly. Occasionally, it also displays ...

Tips for obtaining the unique array element lengths in a JSON array

How can I determine the number of active users in a JSON array that includes both active and inactive user statuses? { "body": { "existing_users": [ { "product": "Pack-2", "user_statu ...

How to implement datepicker on multiple input fields

Below are the two input fields that have datepicker functionality: <div class="row"> <input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="dt" is-open="opened" min="minDate" max="'2015-06-22&apos ...

Having trouble selecting the clicked element after a successful Ajax call, especially when there are multiple elements with the same name

When dealing with multiple elements that share the same class name, I am attempting to target the 'clicked' element upon a successful Ajax return. <td data-name='tom' class="status"><a href="">click< ...

Next.js: Uh-oh! Looks like we've hit an obstacle with Error 413 Request Entity

I've encountered an issue while attempting to upload large files using Next.js. I've set up an onChange function for my file input, and here's the code snippet: const handleFileUpload = () => new Promise(async (resolve) => { if(ref ...

The issue with Jquery.Validate not functioning properly when trying to upload a file

I have integrated jQuery validation into my ASP.NET MVC project, and it is functioning correctly with textboxes. However, I am encountering an issue with file uploads. Below is the code snippet I am using: @model ffyazilim.Management.Model.Credential.Crea ...

Encountering problems due to the addition of an event listener on my webpage

Currently working on a nodejs app utilizing react and encountering an issue when running yarn start. The error message "TypeError: btn_bmi.addEventListener is not a function" keeps popping up. This setup has worked for me before but now I'm unsure abo ...

Optimal code structuring for a javascript plugin

Hey there, I came across some intriguing posts on this topic, but I believe it's a very personal question that requires a tailored answer. So, I'm reaching out to ask you: what is the most effective way to organize my code for a JavaScript plugin ...

Contrasts the differences between an array and an array of objects

Hey there, I've got this object that contains information about some movies const responseFilms = { "page": 1, "results": [ { "adult": false, "backdrop_path": "/cinER ...

Javascript: triggering a self-executing function manually

I have a code snippet similar to the following: var msg="first call"; (function test(msg) { console.log("inside self call"); } )(); msg="second call"; console.log("before inline call"); test(msg); console.log("after inline call"); In thi ...

Discovering similarities within a collection to generate a fresh collection utilizing Java 8

I have a collection of Objects representing Dogs, each with a gender (male or female) indicated as a variable within the Object. My task is to loop through the list of Dogs, and for each male Dog, I must check if there is a matching female Dog based on tw ...

"Organizing an object array based on a specified order array - a step-by-step

My task involves rearranging objects within an array. Let's assume this is the data array provided: const data = [ { id: 'ETHUVMY0m', name: 'item 1', value: 'value 1' }, { id: 'McfTB40vO', name: 'item ...