MongoDB:并非使用$ geoNear从查询返回所有结果

Lou*_*is 7 mongoose mongodb node.js

我收到了这个问题:

 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);
          });
      }
    })
};
Run Code Online (Sandbox Code Playgroud)

该查询应该在特定位置周围检索给定范围内的所有导师(这是来自导师模型的字段,以km为单位的整数,表示导师愿意移动多远).(lat1,lon1).

问题是所有文件都没有退回.经过多次测试后,我注意到只返回距离该位置不到7.5公里的导师,而不是其他导师.即使导师距离10公里并且射程为15公里,他也不会因为他超过7.5公里而返回.

我已经尝试在两个导师之间切换位置(一个返回,一个不是但应该是),看看这是否是造成问题的唯一原因.在我切换它们的位置(lng和loc)之后,之前返回的那个不再,反之亦然.

我真的不明白为什么会这样.

此外,我知道结果大小小于16MB,因为我没有得到所有结果,即使使用allowDiskUse:true.

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

谢谢 !

PS:这是有关领域(loc)的导师模型的一部分:

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
};
Run Code Online (Sandbox Code Playgroud)

用户模型使用两个索引.ID和这个;

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

小智 2

我也有一些类似的问题,就我而言,存在限制问题

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

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

如果您愿意,可以增加限制。希望有帮助