MongoDB:使用$ geoNear

时间:2018-10-16 12:09:43

标签: node.js mongodb mongoose

我得到了这个查询:

 exports.search = (req, res) => {

  let lat1 = req.body.lat;
  let lon1 = req.body.lng;
  let page = req.body.page || 1;
  let perPage = req.body.perPage || 10;
  let radius = req.body.radius || 100000; // This is not causing the issue, i can remove it and the issue is still here


  var options = { page: page, limit: perPage, sortBy: { updatedDate: -1 } }

  let match = {}

  var aggregate = null;

  if (lat1 && lon1) {

    aggregate = Tutor.aggregate([
      {
        "$geoNear": {
          "near": {
            "type": "Point",
            "coordinates": [lon1, lat1]
          },
          "distanceField": "distance", // this calculated distance will be compared in next section
          "distanceMultiplier": 0.001,
          "spherical": true,
          "key": "loc",
          "maxDistance": radius
        }
      },
      {
        $match: match
      },
      { "$addFields": { "islt": { "$cond": [{ "$lt": ["$distance", "$range"] }, true, false] } } },
      { "$match": { "islt": true } },
      { "$project": { "islt": 0 } }
    ])
    // .allowDiskUse(true);
  } else {
    aggregate = Tutor.aggregate([
      {
        $match: match
      }
    ]);
  }



  Tutor
    .aggregatePaginate(aggregate, options, function (err, result, pageCount, count) {

      if (err) {
        console.log(err)
        return res.status(400).send(err);
      }
      else {

        var opts = [
          { path: 'levels', select: 'name' },
          { path: 'subjects', select: 'name' },
          { path: 'assos', select: 'name' }
        ];
        Tutor
          .populate(result, opts)
          .then(result2 => {
            return res.send({
              page: page,
              perPage: perPage,
              pageCount: pageCount,
              documentCount: count,
              tutors: result2
            });
          })
          .catch(err => {
            return res.status(400).send(err);
          });
      }
    })
};

该查询应该在某个位置附近检索给定范围(这是教师模型中的一个字段,以km为单位的整数,指示教师愿意移动的距离)内的所有教师。 (lat1,lon1)。

问题是未退回所有文档。经过多次测试后,我注意到仅返回距离该地点大约不到7.5公里的补习生,而不是其他补习生。即使家教老师在10公里之外且距离在15公里之内,他的距离也不会超过7.5公里。

我尝试过在两个导师之间切换位置(一个返回,另一个应该但不应该),以查看这是否是导致问题的唯一原因。在切换了他们的位置(lng和loc)之后,之前返回的那个不再是了,反之亦然。

我真的不知道为什么会这样。

此外,我知道结果的大小小于16MB,因为即使使用allowDiskUse:true也无法获得所有结果。

如果您对我为什么没有获得所有结果有任何其他想法,请不要犹豫!

谢谢!

PS:这是带有相关字段(位置)的导师模型的一部分:

import mongoose from 'mongoose';
import validate from 'mongoose-validator';
import { User } from './user';
import mongooseAggregatePaginate from 'mongoose-aggregate-paginate';

var ObjectId = mongoose.Schema.Types.ObjectId;


var rangeValidator = [
    validate({
        validator: (v) => {
            v.isInteger && v >= 0 && v <= 100;
        },
        message: '{VALUE} is a wrong value for range'
    })
];



var tutorSchema = mongoose.Schema({
    fullName: {
        type: String,
        trim: true,
        minlength: [1, 'Full name can not be empty'],
        required: [true, 'Full name is required']
    },
    location: {
        address_components: [
            {
                long_name: String,
                short_name: String,
                types: String
            }
        ],
        description: String,
        lat: Number,
        lng: Number

    },
    loc: {
        type: { type: String },
        coordinates: []
    },


});

tutorSchema.plugin(mongooseAggregatePaginate);
tutorSchema.index({ "loc": "2dsphere" });
var Tutor = User.discriminator('Tutor', tutorSchema);


module.exports = {
    Tutor
};

用户模型正在使用两个索引。 ID和这个;

db['system.indexes'].find() Raw Output
{
  "v": 2,
  "key": {
    "loc": "2dsphere"
  },
  "name": "loc_2dsphere",
  "background": true,
  "2dsphereIndexVersion": 3,
  "ns": "verygoodprof.users"
}

3 个答案:

答案 0 :(得分:2)

我也有类似的问题,我的情况是限额有问题

https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/

默认限制为100(可选。要返回的最大文档数。默认值为100)。

如果需要,可以增加限制。希望对您有帮助

答案 1 :(得分:1)

您正在使用spherical: true,其语义不同于平面地理空间查询。

此外,由于您使用的是GeoJSON对象,而不是普通坐标,因此距离必须以米(或千米,因为您使用的是.001乘数)来提供

使用spherical: true时,它使用$nearSphere查询:https://docs.mongodb.com/manual/reference/operator/query/nearSphere/#op._S_nearSphere

spherical: false中,mongo使用$near查询:https://docs.mongodb.com/manual/reference/operator/query/near/#op._S_near

由于使用的是纬度/经度,即平面坐标,因此应禁用球面选项。

答案 2 :(得分:0)

"spherical": true情况下$geoNear返回的距离以弧度表示,因此您需要将"distanceMultiplier": 6371更改为等于地球半径,以Km为单位。