In MongoDB (JavaScript), perform querying operations on a single document attribute if it exists; otherwise, use another property

Imagine having the following entries in your "Request" collection:

{
  pickup: {
    coords: null
  },
  meetup: {
    coords: [ someLng, someLat ]
  }
},
{
  pickup: {
    coords: null
  },
  meetup: {
    coords: [ someLng, someLat ]
  }
},
{
  pickup: {
    coords: [ someLng, someLat ]
  },
  meetup: {
    coords: [ someLng, someLat ]
  }
}

The objective is to present the user with a sorted request list based on distance from their location, starting from the nearest request.

If pickup.coords exists, it should be used as the positional reference for subsequent calculations; otherwise, meetup.coords should be used.

I attempted to implement this using $cond, but encountered an error and am unsure about its correct usage.

This is what I thought could work:

const query = {
  $cond: {
    if: {
     'pickup.coords': { $exists: true }
    },
    then: {
      // use pickup.coords as reference for distance calculation
    },
    else: {
      // use meetup.coords as reference for distance calculation
    }
  }
}

const requests = await Request.find( query )

Error:

unknown top-level operator: $cond

The final implementation will likely involve more complexity, including pagination using limit and utilizing the $near operator along with indexing. But getting through this initial step would be a good start :-)

Any assistance you can offer would be greatly appreciated!

Answer №1

Update your application to format documents in a way that aligns with the queries you want to perform. Include an additional field for storing coordinates that will be used in searches:

{
    pickup: {
      coords: null
    },
    meetup: {
      coords: [ someLng, someLat ]
    },
    _search: {
      coords: [ someLng, someLat ]  
    }
  },
  {
    pickup: {
      coords: null
    },
    meetup: {
      coords: [ someLng1, someLat1 ]
    },
    _search: {
        coords: [ someLng1, someLat1 ]
    }
  },
  {
    pickup: {
      coords: [ someLng2, someLat2 ]
    },
    meetup: {
      coords: [ someLng3, someLat3 ]
    },
    _search: {
        coords: [ someLng2, someLat2 ]
    }
  }

Create an index on this field:

db.collection.createIndex( { _search : "2dsphere" } )

Perform searches using this field:

db.collection.find(
   {
     _search: {
        $nearSphere: {
           $geometry: {
              type : "Point",
              coordinates : [  someLng4, someLat4 ]
           }
        }
     }
   }
)

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

What is the best way to have my transparent navigation bar float on top of my background in a parallax-scrolling website?

Currently, I am working on creating a website with a navigation bar that has no background and floats on top of a background image. However, I am facing an issue with my parallax-scrolling website. Whenever the page is scrolled to the second section, the n ...

Creating a dashed line in Three.js that remains uniform relative to the camera

I am currently working on showcasing geometric figures in 3D using three.js. When manually drawing hidden lines as dashed lines, the 'dashes' appear to be consistent for all of them. Whether it's a line parallel to the camera plane or one t ...

Incorporating Vue.js components into PHP applications

I am currently working on a project using PHP in conjunction with Vue.js and vue-router. In my PHP form handler, I have implemented functionality to send emails. What I am trying to achieve is redirecting the user to a specific component within my Vue ap ...

Having issues with the link page in react-router-dom?

Currently, I am utilizing the react-router-dom library to manage routers. However, I have encountered an issue where linking to another page does not change the page, but instead adds the new page right after the previous one as shown in the image below. W ...

The class instances are not invoking the decorators

I'm experiencing issues with my decorators. It seems that the decorators are not being invoked on every instance of the class. While I understand that decorators are called during declaration time, I am wondering if there is a way to call them for eac ...

How can I position a div to always display directly above another div?

I am currently working on centering a div and would like to utilize this jQuery function... jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", (($(window).height() - this.outerHeight()) / 2) + ...

What can be done to ensure that the value from a promise is retained and available for use in

Currently, I am executing a database query and then manipulating the data to obtain a single numeric value. This value is essential for use in a subsequent array. The current definition of the array appears as follows (see below). The issue at hand is tha ...

The color of the background does not remain changed permanently

I'm having an issue where the background color changes when I click a button, but reverts back almost immediately to its original color. How can I ensure that the new color stays permanently? Here is a simple JavaScript function you can use: functio ...

Struggling with implementing checkboxes within an HTML div using JavaScript

Being a newcomer to programming, I am facing some challenges with HTML/JS. My goal is to create a dynamic checkbox list for adding tasks to complete. Despite researching on at least 10 websites, I haven't been able to make it work. I have thoroughly c ...

Display a list of dates within a specified range using the ng

Utilizing the ng-repeat directive to connect data with a filter for name search: <div ng-repeat='myoldrecs in myoldrec | filter:q as results '>......</div> $scope.myoldrec = [{name:ccc,date:13-02-2016},{name:ddd,date:14-02-2016}]; &l ...

Mongoose currency does not display fractional values

Struggling to implement a Schema with a 'price' field using Mongoose currency by following the guidance in the documentation. However, the output is displaying prices without two decimals (e.g., 499 instead of 4.99). Surprisingly, when I use cons ...

Tips for Verifying Checkbox in Angular 5

When attempting to validate the checkboxes in a form with different fields, I encounter an issue. The HTML code for the form is as follows: <div class="form-group"> <label class="login_label">Courses</label> <span style="col ...

A helpful guide on Sending parameters to a route using an object

I am attempting to transfer data with passing parameters from page1 to page2. Below is the code snippet from page1 : axios({ method: 'post', url: "http://127.0.0.1:8000/api/masuk", data: { ...

Displaying divs depending on dropdown selection - Troubleshooting script issue

When I try to display certain divs based on dropdown selection using the script below, it works fine on a simple page. However, when I implement it on my current development page, it completely messes up the layout, turning everything black and adding stra ...

Code snippet for a click event in JavaScript or jQuery

I initially wrote the code in JavaScript, but if someone has a better solution in jQuery, I'm open to it. Here's the scenario: I have multiple questions with corresponding answers. I want to be able to click on a question and have its answer dis ...

Creating a unique tooltip component for ag-grid with the use of Material tooltips

I am facing an issue with the current angular ag-grid tooltip example, as it is not functioning properly. https://stackblitz.com/edit/angular-ag-grid-tooltip-example-fb7nko Utilizing Javascript/typescript in Angular 8 with the latest ag-grid release. I h ...

Utilizing lodash to Filter Arrays Within Arrays

Let's take a look at the JSON structure provided below. comapany : ABC Emp Info:[ { empName: D, empID:4 salary[ { year: 2017, ...

How can I retrieve a DOM object following an AJAX request?

My AJAX call fetches and appends HTML content to the current page. I hope to access this newly added HTML using standard jQuery selectors. Here's my desired approach... $.ajax({ url: url, success: function(data) { $('body').app ...

What is the process for activating the quasar timepicker once a user has selected a time?

The functionality of the timepicker in Quasar doesn't quite meet my expectations. I don't want to add another library just for this feature. The main issue I have is that it doesn't close automatically after selecting a time. I managed to fi ...

Tips for applying custom gradient colors and styles to React Native's LinearGradient component

"react-native-linear-gradient" - tips on passing colors and styles as props interface Props { // gradientColors:string[] gradientColors:Array<string> } const BaseButton: React.FC<Props> = ({ gradientStyle ,gradientColors} ...