[英]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.