mongodb – use geoNear without omitting non 2dsphere indexed rows

When using geoNear, all rows which do not have location (not a part of 2dsphere index) are omitted.

How to use geoNear to get nearest results but also show other rows that do not have location? The rows which do not have a location should be ranked lower in the results.

.collection('users')
.aggregate([
  {             
    $geoNear: {
       near: { type: "Point", coordinates: [userLocArray[0], userLocArray[1]]},
       distanceField: "dist.calculated",
       spherical: true,
       //maxDistance: matchDistance,
    }
  },

Example documents (In the example below, the users xyz and mmm are omitted by geoNear because they do not have location field. I just wanted them to be ranked lowest but not completely omitted.

   db={
      users: [
        {
          _id: "abc",
          name: "abc",
          group: 1,
          location: {
            type: "Point",
            coordinates: [
              53.23,
              67.12
            ]
          },
          calculatedDist: 112
        },
        {
          _id: "xyz",
          name: "xyyy",
          group: 1,
          calculatedDist: 13
        },
        {
          _id: "123",
          name: "yyy",
          group: 1,
          location: {
            type: "Point",
            coordinates: [
              54.23,
              67.12
            ]
          },
          calculatedDist: 13
        },
        {
          _id: "rrr",
          name: "tttt",
          group: 1,
          location: {
            type: "Point",
            coordinates: [
              51.23,
              64.12
            ]
          },
          calculatedDist: 14
        },
        {
          _id: "mmm",
          name: "mmmm",
          group: 1,
          calculatedDist: 14
        },

      ]
    }

>Solution :

You can simply add another $match stage at the end of pipeline to choose those documents without location

db.users.aggregate([
  {
    "$geoNear": {
      "near": {
        "type": "Point",
        "coordinates": [
          53.23,
          67.12
        ]
      },
      "distanceField": "d"
    }
  },
  {
    "$unionWith": {
      "coll": "users",
      "pipeline": [
        {
          "$match": {
            "location": null
          }
        }
      ]
    }
  }
])

Yes, you are right that Mongo Playground cannot demonstrate 2d sphere index behaviour. But I put it here nevertheless.

Leave a Reply