• nodejs+mongo 实现搜附近的人


    参考网址:http://blog.csdn.net/huangrunqing/article/details/9112227

    用mongo作为存储,来实现搜索附近的人具有先天的优势,

    MongoDB原生支持地理位置索引,可以直接用于位置距离计算和查询。

    另外,它也是如今最流行的NoSQL数据库之一,除了能够很好地支持地理位置计算之外,还拥有诸如面向集合存储、模式自由、高性能、支持复杂查询、支持完全索引等等特性。

    先看一下我在mongo中的数据存储格式:

    /* 0 */
    {
      "_id" : "1",
      "username" : "hyw",
      "address" : "花园村",
      "location" : [113.676557, 34.744776],
      "bloodType" : "O",
      "nickname" : "皇甫",
      "xz" : "摩羯座",
      "tel" : "123456",
      "birthday" : "1989-12-13",
      "sex" : "0",
      "email" : "123456@qq.com"
    }
    
    /* 1 */
    {
      "_id" : "999",
      "username" : "uiouio",
      "address" : "pppppp",
      "location" : [113.594452, 34.742136],
      "bloodType" : "x",
      "nickname" : "oooo",
      "xz" : "射手",
      "tel" : "909090",
      "birthday" : null,
      "sex" : "男",
      "email" : "uuuu121"
    }
    

      其实利用mongo搜索附近的人的最主要的命令是geoNear命令,解释如下:

    geoNear返回结果集中的dis,如果指定了spherical为true, dis的值为弧度,不指定则为度。不指定sphericial,结果中的dis需要乘以111换算为km:
    指定 spherical为true,结果中的dis需要乘以6371换算为km:
    --获取附近500米(0.5公里)的人
    db.runCommand({geoNear:'userInfo',near:[113.676557,34.744778],spherical:true,maxDistance:0.5/6371,distanceMultiplier: 6371,query:{xz:'双鱼'},num:10});

    其中userInfo为存储地理位置信息的集合(即关系型数据库中所谓的表),maxDistance 指定搜索的最大半径范围,query 指定其他搜索条件,num(也可以是limit)指定返回结果的条数,其他具体的参数可以参考官方文档说明http://docs.mongodb.org/manual/reference/command/geoNear/#dbcmd.geoNear

    nodejs 代码就非常简单了:

    /**
         * 获取附近的人
         */
        getNearUser:function(queryParams,callback){
            var command = {};
            command.geoNear = 'userInfo';
            command.spherical = true;//如果指定了spherical为true, dis的值为弧度,不指定则为度
            command.distanceMultiplier = 6371000;//指定 spherical为true,结果中的dis需要乘以6371换算为km:查询时指定 distanceMultiplier ,它会将这个参数乘以距离返回
            var location = [];
            location.push(queryParams.lng);
            location.push(queryParams.lat);
            command.near = location;
            if(queryParams.distance){
                command.maxDistance = queryParams.distance/6371000;
            }
            if(queryParams.rows){
                command.num = queryParams.rows;
            }
            if(queryParams.xz){
                var queryEntity = {};
                queryEntity.xz = queryParams.xz;
                command.query = queryEntity;
            }
    
            db.mongoConn.command(command,function(err,result){
                if(err){
                    return callback(err);
                }else{
                    callback(null,result.results);
                }
            });
        }
    

      

  • 相关阅读:
    <<剪绳子>>题解
    P5743 小猴吃桃 题解
    注意C++中的int与long long 的乘法
    数组初始化方法总结
    一维差分和二维差分
    一维前缀和与二维前缀和
    例2-6 字母转换
    例1-11 评测机队列
    golang ---查找字串实例 IP address
    mongodb ---加减等操作
  • 原文地址:https://www.cnblogs.com/angryprogrammer/p/4264127.html
Copyright © 2020-2023  润新知