Trying to use Geo Spatial queries of Mongo DB my documents are like: Location document:
{
"_id": ObjectId("57062a9253e564e0d522f001"),
"geofences": [
{
"geofenceId": "geoFence1",
"loc": {
"type": "Polygon",
"coordinates": [
[
[
-11900093200000002,
33.53589500000004
],
[
-118.96275899999999,
33.48520500000012
],
[
-118.98051199999996,
33.42859300000009
],
[
-119.05307099999987,
33.411024
],
[
-119.094128,
33.426871999999946
],
[
-119.10887899999999,
33.451151000000095
],
[
-119.10721499999987,
33.50002300000011
],
[
-119.11894899999999,
33.500022
],
[
-119.10871799999988,
33.519264000000135
],
[
-119.07014300000003,
33.536415999999974
],
[
-119.00093200000002,
33.53589500000004
]
]
]
}
}
]
}
Asset Document:
{
"_id": ObjectId("536b150c30048054e3480789"),
"loc": {
"type": "Point",
"coordinates": [
-120.954436,
37.625814000000005
]
},
"name": "kingize",
"type": "priceless",
"code": "pwd"
}
they get inserted properly but when i am trying to do following:
var myloc = db.locations.find().next()
db.assetlocation.find( { loc : { $geoWithin : { $geometry : myloc.geofences } } })
I am getting:
error: {
"waitedMS" : NumberLong(0),
"ok" : 0,
"errmsg" : "Point must only contain numeric elements",
"code" : 2
}
I think this error would have come on the insert statements only but to my surprise they worked just perfectly.
答案 0 :(得分:1)
问题是"geofences"
集合中包含的文档中的"locations"
属性实际上是一个“数组”。因此,直接形式的数据不适合与$geoWithin
一起使用。
为了向$geoWithin
提供"loc"
数据,您需要实际迭代"geofences"
的每个数组元素并传入每个元素的数据:
var results = [];
var cursor = db.locations.find();
// Iterate the cursor
while ( cursor.hasNext() ) {
var doc = cursor.next();
// Iterate each geofences element
doc.geofences.forEach(function(fence) {
// Query to array of results
var assets = db.assetlocation.find({
"loc": {
"$geoWitin": {
"$geometry": fence.loc
}
}
}).toArray();
// Append to the total results
results = results.concat(assets);
});
}
// Print all results
printjson(results);
因此,您需要“首先”获取每个结果文档中的每个数组元素,然后您可以使用包含的数据在"assetlocation"
集合上提供查询并收集所获得的结果。
答案 1 :(得分:1)
您向查询传递了错误的参数。不要传递geofences
对象,而是传递包含实际坐标和几何类型的geofences[0].loc
字段。
由于geofenches
是一个数组,因此您可以遍历以获得单个几何体。
请尝试以下代码段,它应该使用所选条件获取文档。
var myloc = db.locations.find().next()
var coor = myloc.geofences[0].loc;
db.assets.find( { loc : { $geoWithin : { $geometry : corr } } })