繁体   English   中英

MongoDB / Mongoose - 使用geoNear和子文档进行聚合

[英]MongoDB/Mongoose - Aggregation with geoNear & subdocuments

我正在使用node-geoip模块并执行聚合查询。 我执行查询的模式如下所示:

var mongoose = require('mongoose');
require('./location.js');

module.exports = mongoose.model('Region',{
    attr1: Number,
    attr2: String,
    attr3: String,
    locations:[mongoose.model('Location').schema]
});

var mongoose = require('mongoose');

module.exports = mongoose.model('Location',{
    attr1: Number,
    latlong: { type: [Number], index: '2d' },
});

我需要在聚合查询中执行$ geoNear操作,但我遇到了一些问题。 首先,这是我的聚合方法:

var region = require('../models/region');

var geo = geoip.lookup(req.ip);

region.aggregate([
    {$unwind: "$locations"},
    {$project: {
        attr1 : 1,
        attr2 : 1,
        locations : 1,
        lower : {"$cond" : [{$lt: [ '$locations.attr1', '$attr1']}, 1, 0]}
    }},
     {
      $geoNear: {
         near: { type:"Point", '$locations.latlong': geo.ll },
         maxDistance: 40000,
         distanceField: "dist.calculated"
      }
     },
    { $sort: { 'locations.attr1': -1 } },
    {$match : {lower : 1}},
    { $limit: 1 }
], function(err,f){...});

我得到的第一个问题是显然geoNear必须处于管道的第一阶段: exception: $geoNear is only allowed as the first pipeline stage 所以我的问题是,我可以在子文档中执行geoNear搜索而不需要展开吗? 如果是这样,怎么样?

我得到的另一个错误信息是errmsg: \\"exception: 'near' field must be point\\" 这意味着什么,它对我的​​代码意味着什么? 我尝试过使用near

near: { type:"Point", '$locations.latlong': geo.ll },

首先是免责声明:我不是Node / Mongoose专家,所以我希望你能将一般格式翻译成Node / Mongoose。

对于错误:

 errmsg: "exception: 'near' field must be point"

对于'2d'索引,这不能是GeoJson点,而是需要是“遗留坐标对”。 例如,

{
  "$geoNear": {
    "near": geo.ll,
    "maxDistance": 40000,
    "distanceField": "dist.calculated"
  }
}

如果你想使用GeoJSON,你需要使用'2dsphere'索引。

通过该更改,$ geoNear查询将与查询中的点数组一起使用。 shell中的一个例子:

> db.test.createIndex({ "locations": "2d" })
> db.test.insert({ "locations": [ [1, 2], [10, 20] ] });
> db.test.insert({ "locations": [ [100, 100], [180, 180] ] });
> db.test.aggregate([{
  "$geoNear": {
    "near": [10, 10],
    "maxDistance": 40000,
    "distanceField": "dist.calculated",
    num: 1
  }
}]);
{
  "result": [{
    "_id": ObjectId("552aaf7478dd9c25a3472a2a"),
    "locations": [
      [
        1,
        2
      ],
      [
        10,
        20
      ]
    ],
    "dist": {
      "calculated": 10
    }
  }],
  "ok": 1
}

请注意,每个文档(最近点)只能获得一个距离,这在语义上与放松时不同,然后确定到每个点的距离。 我无法确定这对您的用例是否重要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM