Mongodb – Efficient way to store geographical routes in MongoDB

mongodbspatial

I need to store a taxi route into MongoDB, however I'm not sure what is the best way to do this.

Since the route is only needed for the taxi order, the first idea I had is to store it in the order, this would make the retrieval quite fast, since I won't need to join the order collection with the route collection. As well as that, the route can be stored in a simplified way for example:

{
   order_id: 1,
   ...
   route: [
        [ 1567767312, 58.542454, 110.15454, 45 ], //timestamp, lat, long, speed
        ...
        [ 1567768312, 59.448488, 10.484684, 20 ]

   ]
}

If say the measurement is done every 2 seconds, an average 15 min ride would be 450 points, which is not a lot.

However, I read that MongoDB does not like when documents are very different in sizes and since the route can be different all the time, this might cause issues as the order number grows.

The other obvious approach was to have a separate collection to store each reading a separate document:

{
    timestamp: "2019-09-06T10:49:38+00:00",
    coordinates: [ 58.45464, 128.45465 ],
    order_number: 1
}

With indexing, this should not be much slower in terms of fetching or writing than the method above. However, this will occupy way more space and the collection might grow really fast.

Just as clarifications. The route is only used for displaying it on the map when somebody opens the order, no need for geo queries.

Best Answer

The right way to store a taxiroute in a MongoDB is to use a GeoJSON object and a LINESTRING

{ type: "LineString", coordinates: [ [ 40, 5 ], [ 41, 6 ] ] }

Using this method you can make use of Spatial Queries like $geointersects and $geonear, and Spatial Indexes. All of that said, you're probably better off migrating to a database that focuses more on this kind of stuff, like PostgreSQL.