i'm experimenting with mongodb and geospatial queries. I made the following collection:
shape> db.shape.find()
[
{
_id: ObjectId("61ab50d2056b5357b5e23e56"),
name: 'Point1',
structure: { type: 'Point', coordinates: [ 2.5, 2.5 ] }
},
{
_id: ObjectId("61ab5337056b5357b5e23e57"),
name: 'Point2',
structure: { type: 'Point', coordinates: [ 5, 5 ] }
},
{
_id: ObjectId("61ab533e056b5357b5e23e58"),
name: 'Point3',
structure: { type: 'Point', coordinates: [ 9, 9 ] }
},
{
_id: ObjectId("61ab5b4d056b5357b5e23e64"),
name: 'square',
structure: {
type: 'Polygon',
coordinates: [ [ [ 0, 0 ], [ 0, 5 ], [ 5, 5 ], [ 5, 0 ], [ 0, 0 ] ] ]
}
}
]
then i tried the following:
var square = db.shape.find({name :"square"});
db.shape.find({structure : { $geoWithin : { $geometry : square.structure}}});
and i get this error:
MongoServerError: unknown geo specifier: $geometry: null
why is $geometry null?
Thanks in advance
While processing the query,
square.structureis getting replaced withnullbecause you are trying to access that variable in wrong way.In that
squarevariable you are storing results returned byfind()method.find()method returns a cursor and we need to use cursor methods (likeforEach) to access the containing documents. Where asfindOne()returns a single document which can be accessed directly.So, you can:
findOne()instead offind()orsquare.forEach(function(mydoc){<iterate through cursor here>})I have copied your data and tested your query with
findOne()and it worked well.