$geoWithin query on array returning null

Hi everyone!

I’m trying to perform a $geoWithin query on the location field of the last item of an address array that looks like below…

address: [
  {
    street: "4 Pivet Drive",
    city: "Little Whinging",
    state: "Surrey",
    location: {
      type: "Point",
      coordinates: [1, 1]
    }
  },
  {
    street: "Hogwarts Castle",
    city: "Scottish Highlands",
    state: "London",
    location: {
      type: "Point",
      coordinates: [2, 2]
    }
  },
]

I’m using nodejs and mongoose, and below is how I wrote the code.

const result = await User.findOne(
      {
        _id: userId,
        "address.-1.location": {
          $geoWithin: {
            $geometry: {
              type: "Polygon",
              coordinates: [[[0, 0], [0, 4], [4, 4], [4, 0], [0, 0]]],
            },
          },
        },
      }
    );

The result is null.

What is the correct way to implement this or will the query not work on an array?

Thank you.

The -1 index position is not valid. With the data provided this query will work with:

"address.location":
"address.0.location":
"address.1.location":

Thanks for your response Chris, but I need to perform the query on the last item in the address array at any given point. Is there a way to achieve this?

For what you currently have the aggregation below may work for you.

Having a field with the current address and a separate field with the address history may be more useful

db.collection.aggregate([
  {
    $match:
      {
        _id:"hpotter",
      },
  },
  {
    $set:
      {
        lastAddr: {
          $last: "$address",
        },
      },
  },
  {
    $match:
      {
        "lastAddr.location": {
          $geoWithin: {
            $geometry: {
              type: "Polygon",
              coordinates: [
                [
                  [0, 0],
                  [0, 4],
                  [4, 4],
                  [4, 0],
                  [0, 0],
                ],
              ],
            },
          },
        },
      },
  },
  {
    $unset:
      "lastAddr",
  },
])
1 Like

Thank you, Chris, for your help. It works fine now

1 Like

Please mark as solved so this topic will close.

1 Like

How do I do that please?