Error: The geoNear command was unsuccessful due to the presence of multiple 2d indexes

My goal is to fetch documents from a collection based on distance. I attempted to utilize the $geoNear aggregation, but encountered errors (while using node.js and Postman) or received zero records as output.

Example Document:

{
    "_id" : ObjectId("5cc37692fe9fd54b3cd136c9"),
    "category" : "art",
    "description" : "an eastbound description for The soda event.",
    "geometry" : {
        "type" : "Point",
        "coordinates" : [ 
            3.60178480057443, 
           6.46123057784917
        ]
    }
    "__v" : 0
}
.
.

Data Model:

const GeoSchema = new Schema({
  type: {
    type: String,
    default: "Point"
  },
  coordinates: {
    type: [Number],
    index: "2dsphere"
  }
}, { _id: false });

const EventSchema = new Schema({
  category: String,
  description: String,
  geometry: GeoSchema,
});

Query Example

db.events.aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: [3.60178480057443, 6.46123057784917] },
        distanceField: "dist",
        maxDistance: 90000,
        spherical: true
     }
   }
]);

After running the query above, an empty array (on Postman) or no results are returned, occasionally showing this error message:

{
    "name": "MongoError",
    "errmsg": "exception: geoNear command failed: { ok: 0.0, errmsg: \"more than one 2d index, not sure which to run geoNear on\" }",
    "code": 16604,
    "ok": 0
}

If the error occurs, I execute the db.events.dropIndex function. When I followed the examples from the documentation exactly, it worked smoothly. Can anyone provide guidance on how to get the $geoNear function functioning correctly? I've been grappling with it all day.

Answer №1

Having more than one 2dsphere index on a single collection is not supported. If you have created 2dsphere indexes on multiple fields, remove one of them by running the following command:

db.getCollection('test').createIndex({ "loc": "2dsphere" }) 

To check the list of indices, use this command:

db.getCollection('test').getIndexes()

Update:

If your collection has multiple $geoNear indices, you can specify the field to search with using the key parameter.

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

Bootstrap3 Remote Modal experiencing conflict due to Javascript

Utilizing a bootstrap modal to showcase various tasks with different content but the same format is my current goal. However, I am encountering an issue when attempting to make the textareas editable using JavaScript. The conflict arises when I open and cl ...

Having an issue with ng-model not functioning correctly in md-menu with AngularJS material

I'm currently using md-menu from Angular Material and I have integrated a search box with ng-model in the list. However, I am facing an issue where I cannot access ng-model because 'md-menu-content' is out of scope. Here is my code: <div ...

Top approach for Constructing Angular Front-End Forms with User Input

Greetings to all who happen upon this message, thank you for taking the time to potentially offer assistance! In my past experiences working with Wordpress (PHP), I utilized a plugin called Advanced Custom Fields from advancedcustomfields.com. This plugin ...

emulating the behavior of a synchronous XmlHttpRequest

While I have taken the time to explore similar questions like Pattern for wrapping an Asynchronous JavaScript function to make it synchronous & Make async event synchronous in JavaScript, I want to ensure that I consider all potential solutions. Is it ...

Issue with redirecting after a POST request is not functioning properly

After creating an API in node and defining a method to handle POST requests, I found that returning res.redirect(redirectUrl); from the method causes the browser to redirect back to the API instead of the intended URL. Despite my efforts, this issue persi ...

Setting up instagram-node-lib for managing subscriptions

I am currently working on implementing real-time updates for a specific hashtag and displaying the image on the screen. However, I am facing issues setting up my node.js server using the instagram-node-lib module. Even after running the file (node server.j ...

Adding items to objects in MongoDB and Node.js using Mongoose

In the model I have created, there is a structure like this: subjects: { Mathematics: { questionsanswered: [ "x+2=3, solve for x please", "How do you write an expression that represents all quadrantal angles?" ], ques ...

I am looking to implement a new REST method through a Spring Data MongoDB repository that includes ALPS/HATEOAS metadata. How can I go about doing

How can I make a new method in a MongoRepository extension class accessible in the generated REST API with ALPS/HATEOAS metadata? Starting with a standard Spring Data MongoDB repository: public interface CollectionRepository extends Repository<Collect ...

What led to the decision for the two distinct chart elements to merge into a single container?

In the process of creating a dashboard using React.js and d3.js, I encountered an interesting issue that perplexed me for quite some time. Below is the Scatterplot.js code written in d3.js: import React, { Component } from "react" import * as d3 from "d3 ...

Is there a solution to fix the issue with IE causing hover effects not to

I'm currently in the process of designing a website, and I have implemented some image hover effects that reveal elements within the image when you hover over it. These effects are functioning correctly on Chrome, Safari, and Firefox; however, they ar ...

Using JavaScript and Tampermonkey to convert strings from an HTML element into an array

I am trying to change the names of months into numbers and place them in a table cell on a website. I thought using an array would make it easier to reference the month names by their corresponding array numbers, allowing me to add table tags before and af ...

Continue running web AJAX request in Android browser while it is minimized

I need help with my AJAX call var tid = setInterval(mycode, 2000); function mycode() { $.ajax({ url:'/ajx.php', type: "GET", success: function (data) { }, ...

Opacity error with jQuery slider specifically affecting Google Chrome browser

My Magento site features a custom-built slider that is both responsive and has unique touch behavior. The desired behavior for the slider is as follows: A three-image slider where the middle image has an opacity of 1.0, while the other two images have an ...

The error message indicates a problem with accessing the property 'findOne' of an undefined value in mongoose

I've been working with rethinkdb, but as it's becoming outdated, I'm considering transitioning to mongodb. Whenever I run my prefix command, I encounter this error and here is the code snippet: const { Guild } = require('../../models/Gu ...

What is the best way to combine a JSON response object with the variable J inside a for loop?

Received a JSON response as follows: { "name" : "chanchal", "login3" : "1534165718", "login7" : "1534168971", "login6" : "1534168506", "login5" : "1534166215", "login9" : "1534170027", "login2" : "1534148039", "lastname" : "khandelwal", ...

The variable "require" has not been declared in npm.js file at line

Apologies if this is a simple issue, but I have not been able to find a solution in my research. I am using the latest release of Bootstrap and have noticed a new file called npm.js compared to previous versions. All Bootstrap files are hosted locally on m ...

Does the AJAX load more feature duplicate the existing data?

I've successfully implemented a PHP code that generates JSON data from WordPress posts in the database. By using AJAX, I'm able to load this JSON on my HTML page without any issues. Now, I want to enhance this functionality by adding a "Load Mo ...

JavaScript can be used to set the active tab index in Internet Explorer

Dealing with IE is a constant struggle for me. My goal is to implement validation that runs from a button within a tab to prevent users from skipping tabs without filling in data, which could potentially cause issues with my database queries. $("[id ...

Is Python being used to track NBA.com stats?

Does anyone have any advice on how to extract NBA.com "tracking" stats using a python script and display them in a simple table? I'm particularly struggling with this specific section of stats on the site. Accessing stats directly from NBA.com can be ...

Error occurs in console when using .getJSON with undefined JSON, but does not happen when using embedded data

Can someone help me understand why I'm getting an 'undefined' response when I use console.log(tooltipValues), but there's no issue with console.log(tooltipJSON). I've noticed that when I embed the data directly in my JS code, ever ...