下面我提到了我用于地图缩小的集合。本文档的latitude
属性下有两个属性,分别为longitude
和location
。使用这两个,我将生成一个名为distance
的新属性。基于此属性,我需要对文档的顺序进行排序。
/* 1 */
{
"_id" : ObjectId("5d7f63b270ba7629d2efcb4f"),
"title" : "AppDividend",
"published" : "2017-03-27",
"authors" : [
{
"firstName" : "Krunal",
"lastName" : "Lathiya"
}
],
"location" : {
"name" : "Dehiwala, Field Ave, Dehiwala-Mount Lavinia, Sri Lanka",
"latitude" : "6.849458",
"longitude" : "79.881154"
},
"categories" : [
"Angular",
"React",
"Vue"
]
}
/* 2 */
{
"_id" : ObjectId("5d7f63ba70ba7629d2efcb50"),
"title" : "Demonuts",
"published" : "2016-12-10",
"authors" : [
{
"firstName" : "Krunal",
"lastName" : "Lathiya"
}
],
"location" : {
"name" : "Paramount Event Spaces, 9th Ln, Sri Jayawardenepura Kotte 11222, Sri Lanka",
"latitude" : "6.884836",
"longitude" : "79.888131"
},
"categories" : [
"Android",
"PHP"
]
}
/* 3 */
{
"_id" : ObjectId("5d7f63c170ba7629d2efcb51"),
"title" : "Scotch.io",
"published" : "2011-12-10",
"authors" : [
{
"firstName" : "Chris",
"lastName" : "Sevilleja"
}
],
"location" : {
"name" : "Royal MAS Arena, Rajakeeya Mawatha, Colombo 00700, Sri Lanka",
"latitude" : "6.905327",
"longitude" : "79.859914"
},
"categories" : [
"React",
"Laravel",
"Vue",
"Angular",
"MongoDB",
"PHP",
"Android"
]
}
这是我的地图缩小功能。
db.blogs.mapReduce(
function() {
for (var index = 0; index < this.authors.length; ++index) {
var author = this.authors[index ];
var ds = getDistance(this.location.latitude,this.location.longitude);
this.distance = ds;
if(this.distance > coverage){
emit(this._id,this);
}
}
},
function(id, values) {
var value;
for (var index = 0; index < values.length; ++index) {
value = values[index];
}
return value;
},
{
out: { inline: 1 },
sort:{ distance: 1},
scope:{
lat1: 6.933762,
lon1: 79.842961,
coverage: 3,
getDistance: function(lat2,lon2){
var R = 6371; // Radius of the earth in km
var dLat = (lat2-lat1)* (Math.PI/180); // deg2rad below
var dLon = (lon2-lon1)* (Math.PI/180);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos((lat1)* (Math.PI/180)) * Math.cos((lat2)* (Math.PI/180)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
}
}
)
当我使用distance属性排序时,结果将不会排序。如何排序结果?