How do I use a geospatial query in the 2.1 MongoDB C# driver?

ぐ巨炮叔叔 提交于 2019-12-05 01:21:18

this is how I do it on my end:

    public IQueryable<TEntity> FindNear<TEntity>(string collectionName, Expression<Func<TEntity, object>> field, double longitude, double latitude, double maxDistanceInKm) where TEntity : IEntity
    {
        var collection = database.GetCollection<TEntity>(collectionName);
        var point = GeoJson.Point(GeoJson.Geographic(longitude, latitude));
        var filter = Builders<TEntity>.Filter.Near(field, point, maxDistanceInKm * 1000);
        return collection.Find(filter).ToList().AsQueryable();
    }

here's the most convenient way to do geospatial aggregation queries for anybody that's interested:

using MongoDB.Driver;
using MongoDB.Entities;
using System;

namespace StackOverflow
{
    public class Program
    {
        public class Place : Entity
        {
            public string Name { get; set; }
            public DateTime Date { get; set; }
            public Coordinates2D Location { get; set; }
            public double DistanceMeters { get; set; }
        }

        static void Main(string[] args)
        {
            //connect to mongodb
            new DB("test");

            //create a geo2dsphere index
            DB.Index<Place>()
              .Key(x => x.Location, KeyType.Geo2DSphere)
              .Option(x => x.Background = false)
              .Create();

            //create and save a place
            var paris = new Place
            {
                Name = "paris",
                Location = new Coordinates2D(48.8539241, 2.2913515),
                Date = DateTime.UtcNow
            };
            paris.Save();

            var eiffelTower = new Coordinates2D(48.857908, 2.295243);

            //find all places within 1km of eiffel tower.
            var places = DB.GeoNear<Place>(
                              NearCoordinates: eiffelTower,
                              DistanceField: x => x.DistanceMeters,
                              MaxDistance: 1000)
                           .SortByDescending(x=>x.Date)
                           .ToList();
        }
    }
}

it generates the following aggregation pipeline:

{
                "$geoNear": {
                    "near": {
                        "type": "Point",
                        "coordinates": [
                            48.857908,
                            2.295243
                        ]
                    },
                    "distanceField": "DistanceMeters",
                    "spherical": true,
                    "maxDistance": NumberInt("1000")
                }
            },
            {
                "$sort": {
                    "Date": NumberInt("-1")
                }
            }

the above is done using MongoDB.Entities convenience library, of which i'm the author of.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!