简体   繁体   中英

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.

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
        }
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM