Easiest way to do this is through shp2pgsql.
If you're uploading to a database that isn't already primed for geometries, you'll have to run CREATE EXTENSION postgis;
Example:
$ shp2pgsql -c -s [SRID] -g geom -I [your_shp_file].shp [new_postgres_table_name] > [output_sql_file_name].sql
$ psql -d [target_database] -f [output_sql_file_name].sql
The SRID I've found to usually be 4326
. But an easy way to find it for a particular shp file is to open the file in QGIS, right click on the layer > Properties > General tab. Under the Coordinate Reference System category you'll find the defaulted CRS and the SRID number should be after "ESPG:"
This is mainly to walk you through a GeoJSON output. If going from PostGIS to shp the recommended way is pgsql2shp
.
Using the elephant icon on the side, click on the "Add PostGIS Layers" button. Connect to your host and select the table where your geometry is. Click "Add".
Once layer is added, right click on the layer in the panel and select "Save As...". Format will be GeoJSON and I usually just change the geometry type from automatic to the actual geometry for good measure.
ogr2ogr is particularly helpful when you have different types of geometries (like points AND polygons) in one file. As far as I know, QGIS doesn't have a way to combine layers and export into one file under the same geom column. It's easier to go straight to geojson without using QGIS as the middleman.
ogr2ogr is part of the GDAL library. The easiest way to install GDAL with the inclusion of the PostgreSQL driver needed for this command is to download GDAL through the GDAL Complete package. You can also install GDAL through Homebrew, but you have to specify a flag to include the PostgreSQL driver and in my opinion the GDAL complete package is cleaner.
After you've downloaded and installed the GDAL framework, run the following commands (as suggested by TileMill):
echo 'export PATH=/Library/Frameworks/GDAL.framework/Programs:$PATH' >> ~/.bash_profile
source ~/.bash_profile
And now you're ready to use ogr2ogr.
ogr2ogr -f "GeoJSON" [output_file_name].json PG:"host=localhost dbname='[dbname]' user='[user]' password='[password]'" -sql "[sql statement]"
In sql
statement, put your SELECT statement here in order to build the table that you want to download. If the table is already the way you want it, the statement will just look like select * from your_table
.