mongodb - Find documents with unique field -
i have collection of addresses geo field (lng/lat). want documents unique geo lng/lat pairs populate google map instance pins. naturally don't want multiple pins sitting in top of each other, need unique lng/lat pairs only.
var mongoose = require("mongoose"), schema = mongoose.schema; var venueschema = new schema({ name: string, street: string, streetnumber: string, postcode: string, suburb: string, state: string, geo: array, // [lng, lat] }); var venue = mongoose.model('venue', venueschema);
using distinct operator, can unique lng/lat. unfortunately query returns array of lng/lat geo points , not documents fields. have no idea business name belongs geo point.
keystone.list('venue').model.find().distinct('geo') .exec(function(err, venues){ if(err){ throw err; } console.log(venues); // array of lat/lng pairs });
how construct query actual documents fields no 2 geo locations same?
you can use aggregate pipeline uses $group
provide distinct-like behavior more flexibility:
keystone.list('venue').model.aggregate([ // group docs geo field, taking first doc each unique geo {$group: { _id: '$geo', doc: { $first: '$$root' } }} ], callback);
$$root
system variable contains input document of pipeline stage. gives first document of each unique geo
value.
Comments
Post a Comment