mongodb 按照距离排序

2016-03-25 14:15:25

  需求是得到一定返回内的活动数据  这个要用到mongoodb的 2d 距离计算功能   需要给活动增加个gps 的距离  先写个demo 吧

var niefengjun=mongoose.Schema({
    id:String,
    title:String,
    gps: [{
        type: Number,
        max: 180,
        min: -180,
        default: 0
    }]
})
niefengjun.index({gps: '2d', name: 1});


插入数据时

var ret={} ;
    ret.id='fdfd333r334343' ;
    ret.title='xiaonie' ;

 var db=new activity.niefengjun(
     {
         id:ret.id,
         title:ret.niefengjun,
         gps:[parseFloat(39.996598),parseFloat(116.457803)]  //前面是纬度 后面是精度
     }
 )


db.save(ret,function(err,body)
{
    console.log(err,body) ;
}


查询时

var q = {
    gps: {
        $near: [3.996598,116.457803],  //前面是纬度 后面是精度
        $maxDistance: 10/ 111.12    //10公里之内的数据
    },
    //typeDef: 1
}
var query=activity.niefengjun.find(q) ;
query.exec(function (err, result) {

    console.log(err,result) ;
})


 特别要注意的是 记录gps里的数据必须是float 型 如果是string 不能计算距离

你打算打赏多少钱呢?

打赏
(微信扫一扫)