Home > Net >  Find centroid of the coordinates stored in GeoJson Mongodb
Find centroid of the coordinates stored in GeoJson Mongodb

Time:01-17

I have recently started working on GeoJson in Mongodb.
I have collection named Restaurants which stores the coordinates of the restaurants in GeoJson POINT object.
Is there a mongodb way of finding the centroid of the collection?

Schema of the Restaurants is as given below:

"use strict";
const mongoose = require("mongoose");

const restaurantSchema = new mongoose.Schema({
  name: {
    type: String,
  },
  geoCoordinates: {
    type: {
      type: String,
      enum: ["Point"],
    },
    coordinates: {
      type: [Number],
    },
  },
  createdTimestamp: {
    type: Date,
    default: Date.now,
  },
  lastUpdatedTimestamp: {
    type: Date,
    default: Date.now,
  },
});

const Restaurants = mongoose.model("Restaurants", restaurantSchema, "Restaurants");

module.exports = {
  Restaurants,
};

Thank you,
KK

CodePudding user response:

One option is to $group and calculate the $avg:

db.collection.aggregate([
  {$group: {
      _id: 0,
      lon: {$push: {$arrayElemAt: ["$location.coordinates", 0]}},
      lat: {$push: {$arrayElemAt: ["$location.coordinates", 1]}}
  }},
  {$project: {
      _id: 0,
      centroid: [{$avg: "$lon"}, {$avg: "$lat"}]
  }}
])

See how it works on the playground example

  • Related