Find the nearest locations in an Array

My document is quite straightforward, containing 3 location objects within an array.

Data:

{
    "_id" : ObjectId("57c3c479a306b3613cf1ee5b"),
    "location_history" : [ 
        {
            "location_name" : "Area 1",
            "date" : 1472447609,
            "_id" : ObjectId("57c3c479ac5a69612f0e0899"),
            "location" : [ 
               24.9532107, 67.1790576
            ]
        }, 
        {
            "location_name" : "Area 2",
            "date" : 1472448059,
            "_id" : ObjectId("57c3c63bac5a69612f0e089c"),
            "location" : [ 
               24.9663937, 67.1462044
            ]
        }, 
        {
            "location_name" : "Area 3",
            "date" : 1472448987,
            "_id" : ObjectId("57c3c9dbac5a69612f0e08a0"),
            "location" : [ 
               -24.987325, 115.1862298
            ]
        } 
}

Question: My goal is to retrieve the nearest locations from this array.

Query Attempted:

db.getCollection('consumers_locations').aggregate([
    {"$unwind": "$location_history"},
    {"$match":{"_id":ObjectId("57c3c479a306b3613cf1ee5b")}},
    {"$project" : { "abc" : "$location_history.location"} },
    { $geoNear: {
        near: { type: "Point", coordinates: [ 24.942785, 67.157855 ] },
        distanceField: "distance",
        query : {"_id" : "_id"},
        uniqueDocs: true,
        includeLocs: "search_history.location",
        maxDistance : 10000
      }
    }
])

However, I encountered an error:

"ok" : 0,
"errmsg" : "$geoNear is only valid as the first stage in a pipeline.",
"code" : 2,
"codeName" : "BadValue"

Expected Result:

{
    "_id" : ObjectId("57c3c479a306b3613cf1ee5b"),
    "location_history" : [ 
        {
            "location_name" : "Area 1",
            "date" : 1472447609,
            "_id" : ObjectId("57c3c479ac5a69612f0e0899"),
            "location" : [ 
               24.9532107, 67.1790576
            ]
        }, 
        {
            "location_name" : "Area 2",
            "date" : 1472448059,
            "_id" : ObjectId("57c3c63bac5a69612f0e089c"),
            "location" : [ 
               24.9663937, 67.1462044
            ]
        }
}

Answer №1

Your current schema doesn't support this operation. Indexes are designed to order documents in a collection, not to sort subdocuments within a document.

I recommend creating a separate location_history collection with references to the parent document in consumers_locations. Here's an example structure for your object:

db.getCollection('location_history').insert([
        {
            "consumer_location": ObjectId("57c3c479a306b3613cf1ee5b"),
            "location_name" : "Area 1",
            "date" : 1472447609,
            "_id" : ObjectId("57c3c479ac5a69612f0e0899"),
            "location" : [ 
               24.9532107, 67.1790576
            ]
        }, 
        {
            "consumer_location": ObjectId("57c3c479a306b3613cf1ee5b"),
            "location_name" : "Area 2",
            "date" : 1472448059,
            "_id" : ObjectId("57c3c63bac5a69612f0e089c"),
            "location" : [ 
               24.9663937, 67.1462044
            ]
        }, 
        {
            "consumer_location": ObjectId("57c3c479a306b3613cf1ee5b"),
            "location_name" : "Area 3",
            "date" : 1472448987,
            "_id" : ObjectId("57c3c9dbac5a69612f0e08a0"),
            "location" : [ 
               -24.987325, 115.1862298
            ]
        } 
]);

In regards to the error message, according to the MongoDB documentation:

You can only use $geoNear as the first stage of a pipeline.

This means that only the first stage of the pipeline can take advantage of indexes.

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

Tips for accessing API data on a standalone HTML page

I am in the process of developing a project that utilizes coingecko's cryptocurrency api. At the moment, I have successfully implemented a chart that showcases the top 100 highest ranking coins. I am now seeking advice on the most efficient method to ...

"Trouble with jquery .load() function not working in older versions of IE (internet explorer

I've been searching for a solution all day, but I'm still encountering this error. We have an Expression Engine setup for a client and we are trying to implement ajax-navigation. We are using the default $.load() function which is working perfec ...

Retrieve the id of an element from a JSON object

Dealing with quotes, single or double, can sometimes pose a challenge. I am working on a JavaScript function that sends data to a PHP file and receives a JSON response. Everything seems to be functioning correctly, except for the part where I need to out ...

Exploring the capabilities of Angular and UIGrid for fetching table information

I have been utilizing Angular along with uigrid, which is an excellent library for displaying data in a tabular format. Everything looks good when displaying the table. However, when I update an item and click on a Save button that triggers a rest service ...

What is the method to prevent the label from closing in the MUI 5 datepicker?

Is there a method to prevent the Material 5 Datepicker from closing when there's a label but no value? Current Scenario: Current Desired Outcome: Expected Sample Code: <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker lab ...

What is the standard root directory in the "require" function's context?

After spending hours struggling to set up a simple "require" command, I've come to the conclusion that var example = require("example") only works if there's an example.js file in the node_modules directory of the project. I'm encountering ...

Steps for validating tab-based list forms and saving them using PHP and AJAX:1. Create a function

I need help with using the jQuery validate plugin to save form data from tab panels in PHP and AJAX. Specifically, I have a list of forms in tab panels and want to save the data according to the active tab. Can anyone provide guidance on how to accomplis ...

Upgrade to the latest version of MaterialUI - V4

After attempting to upgrade materialUI/core from version 3.9.3 to 4.4.1 and materialUI/icons from version 3.0.2 to 4.4.1, I encountered the following error: Error: TypeError: styles_1.createGenerateClassName is not a function I am currently importing crea ...

I'm trying to create a drop-down list in JS that will save selected options to a database using PHP. I'm feeling a bit lost, anyone

My goal is to upload a pdf file with specific options that determine its category. The challenge arises when creating multiple options, as the second option depends on the first choice and involves JavaScript functionality for which I am unsure how to stor ...

How to programmatically set the active pane in an Accordion control using JavaScript in ASP.NET AjaxControl

I am trying to dynamically change the active pane in an accordion using JavaScript. I have come across a method called set_SelectedIndex, but I am having trouble getting it to function properly. Is there a way to determine the supported methods for contr ...

Sending a form using an AngularJS dropdown menu

I have recently started using angularjs and decided to switch out a traditional html <select> box for an angular modal select box. The select box successfully populates with data from a $http ajax request, but I am facing issues with form submission ...

Interactive elements within $ionicLoading

I am attempting to create a clickable button within the $ionicLoading template. I need to execute some code when that button is clicked. Unfortunately, it seems like ng-click is not working. Is there a workaround for this issue? Or am I making a critical ...

Improving the Efficiency of MongoDB ChangeStreams

Can change streams be effectively used for extensive monitoring? I am interested in watching multiple collections with numerous documents that have varying parameters. The goal is to enable multiple users to monitor data they are interested in real-time. W ...

Emscripten WebAssembly: Issue with Exporting Class "Import #13 module="GOT.func" error: the module does not exist as an object or function"

Exploring the potential of WebAssembly in a project as an importable function module, I decided to dive into using C++ with Emscripten. Implementing functions was smooth sailing, but running into obstacles when it comes to classes. My goal is to expose and ...

When attempting to check and uncheck checkboxes with a specific class, the process fails after the first uncheck

I have a set of checkboxes and one is designated as "all." When this box is clicked, I want to automatically select all the other checkboxes in the same group. If the "all" box is clicked again, I would like to deselect all the other checkboxes. Currently ...

What is the best way to incorporate multiple HTML buttons that utilize the same JavaScript function within looped results?

My HTML page contains the following codes: <input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="metin" placeholder="Geben Sie Artikel Nr" style="width: 30%;"/><br/><br/> <input type="button" class="sin ...

"Troubleshooting: Fixing the 'Firebase Cloud Function admin reference is not a function'

I recently attempted to transform the .WriteOn cloud function in my Firebase app into a scheduled cloud function. The goal was to create a function that would run every 4 days to delete messages older than 2 days. While this worked well for the .WriteOn fu ...

What could be causing my React state to not update correctly?

I've been working on integrating the Firebase authentication feature into a React project. The code snippet below shows the component responsible for managing the authentication state. import { useState} from "react"; function useAuth(fbAu ...

variance in efficiency when retrieving a DOM element

While this may not make much of a difference for smaller, simpler DOM elements, the performance impact could be significant when dealing with larger, more complex ones. Is there a noticeable performance gap between storing an element in a variable and cons ...

Unable to retrieve any values using the for each loop in AngularJS

Having an issue with my Angular.js foreach loop. When I use console.log('course data',response.data); the output looks like this: course data [Object, Object, Object] 0: Objectcourse_name: "Master of computer 1: Objectcourse_name: "Bachelor of ...