Gustavo Castro
Gustavo Castro

Reputation: 265

mongodb and geoWithin

The search below works without problems, but when I change to the type of search seeking a position within a polygon it is lost, would have to make some adjustment in the search? I made some attempts will be posting below

db.geom.insert({"polygons":
                  {"type":"Polygon",
                     coordinates:
                      [[[ 17.60083012593064, 78.18557739257812], 
                        [ 17.16834652544664, 78.19381713867188], 
                        [ 17.17490690610013, 78.739013671875], 
                        [ 17.613919673106714, 78.73489379882812],
                        [ 17.60083012593064, 78.18557739257812]
                      ]]
                  }
             }); 

The test I use in mongo.

db.geom.find({polygons:
    {      
    $geoWithin: {
         $geometry: {
            "type" : "Point",
            coordinates: [ 17.3734, 78.4738  ]
         }
      }
   }
 });

The moral is that I have a mapped home and would like to know when a person enters that house, I send the person's position every instant of time to the server. Every moment of time (5 seconds) it runs a testInsideOfHouse.js and checks whether this person has entered or not in the house but the script does not find anything in mongo ... have something I could do more "easy" way using nodejs and mongo ... or am I going the right way?

 Position.find(
        { geo :
                     { $geoWithin : { $box :
                                      [ [ box[0] , box[1] ] ,
                                        [ box[2] , box[3] ] ] } }

    }, function(err, response) {
        if (err) return err;

        console.log(response)

    });    

I found an alternative would be to use a box but it would be a better alternative than using a polygon? I do not quite understand how it would work this box ....

I found that in mongodb does not exist subquery as I would do if instead of having a person to have a list of people with positions and whether they are inside a house or checking ses they are within a list of homes and have return whose house is this person. In mysql or sql would be a query within another query

Thank you for attention

Upvotes: 1

Views: 598

Answers (1)

anhlc
anhlc

Reputation: 14459

You still can use type "Point" as the person's coordinates, but the right operator to use is "$geoIntersects", not "$geoWithin" (as a polygon can't be within a point)

db.geom.find({polygons:
    {      
    $geoIntersects: {
         $geometry: {
            "type" : "Point",
            coordinates: [ 17.3734, 78.4738  ]
         }
      }
   }
 });"

Upvotes: 1

Related Questions