Alvin
Alvin

Reputation: 8499

Find $near location wrong result

I have a business collection, with branch as nested document, location is define as type: [Number] in mongoose:

{
    "_id" : ObjectId("5466f87edb96504c30e910db"),
    "name" : "Microsoft",
    "description" : "Microsoft Redmond",
    "branch" : [ 
        {
            "name" : "Redmond",
            "location" : [ 
                -122.130137,
                47.644702
            ],
            "_id" : ObjectId("5466f87edb96504c30e910dd")
        }, 
        {
            "name" : "Seattle",
            "location" : [ 
                -122.326241, 
                47.599146
            ],
            "_id" : ObjectId("5466f87edb96504c30e910dc")
        }
    ],
    "tags" : [],
    "__v" : 0
}

Now I try to search for nearest to my current location:

db.business.find(
   { "branch.location": { $near: [-122.326412, 47.623022], $maxDistance: 5} }
)

The result should be Seattle at the top, but I am getting all records just like the command : db.business.find().

Am I doing the right thing?

The result I would like is:

           "branch" : [ 
            {
                "name" : "Seattle",
                "location" : [ 
                    -122.326241, 
                    47.599146
                ],
                "_id" : ObjectId("5466f87edb96504c30e910dc")
            },
            {
                "name" : "Redmond",
                "location" : [ 
                    -122.130137,
                    47.644702
                ],
                "_id" : ObjectId("5466f87edb96504c30e910dd")
            }            ]

Upvotes: 0

Views: 71

Answers (1)

Markus W Mahlberg
Markus W Mahlberg

Reputation: 20683

maxDistance is given in meters, whereas the distance between the points is much bigger than 5m. If you values accordingly (I assume you meant miles), the query should work.

Furthermore, your places are stored within a single document. MongoDB won't sort arrays of an document according to the distance. If you had the locations in different documents, they'd be happily sorted by distance.

Upvotes: 2

Related Questions