Rolando
Rolando

Reputation: 62624

How to get unique mongodb?

If I have documents like this:

{firstname:"Jordan", lastname:"Snyder", age:6, homelocation:[<longitude, latitude>]}

In the mongo shell, how do I all the "distinct" firstname's across matching documents of people who live near a specific point (say 1 mile)? I see mongo has a distinct db.collection.distinct(field, query), but all the samples I see for finding anything "near" or "geowithin" (using homelocation field in my case) is using db.collection.find. I don't want all documents, I just want the distinct list of firstnames.

Upvotes: 0

Views: 87

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

The query parameter of distinct uses the same format as the query selector parameter of find. So assuming a 2dsphere index on homelocation you can do something like:

db.test.distinct('firstname', {
    homelocation: {
        $near: {
            $geometry: { type: "Point",  coordinates: [ -73.9667, 40.78 ] },
            $maxDistance: 1600 // In meters
        }
    }
})

Upvotes: 2

Related Questions