gpt4 book ai didi

linq - C#MongoDB "Near"查询

转载 作者:行者123 更新时间:2023-12-04 05:04:11 25 4
gpt4 key购买 nike

我有一个mongo集合,看起来像这样:

{
"_id": {
"$oid": "50e9f38fbd7680c8090bcb4"
},
"guid": "D3G5wQ8RZL",
"lat": 37.503287248864,
"lng": -121.97620341421,

}
我想使用C#linq执行“NEAR”查询

它需要看起来像这样
query = query.Where(x => LinqToMongo.Inject(Query.Near("Location", -96.770401, 32.816774, 20)));

我的问题是-我应该在“位置”中插入什么代码?如何查看以上集合中的积分?

谢谢。

最佳答案

从MongoDB 2.4开始,存储并索引GeoJSON。您可以找到所有概念here

如何在POCO类型上定义GeoJSON属性:

public class Foo
{
public GeoJsonPoint<GeoJson2DGeographicCoordinates> Location { get; set; }
}

示例实例:
var docToInsert = new Foo
{
Location = new GeoJsonPoint<GeoJson2DGeographicCoordinates>(
new GeoJson2DGeographicCoordinates(-121.97620341421, 37.503287248864))
});

$near需要一个地理空间索引,并且由于我们要存储GeoJSON,因此它特别需要一个2dsphere索引:
var collection = //get MongoCollection<Foo> from MongoDatabase object
collection.EnsureIndex(IndexKeys<Foo>.GeoSpatialSpherical(x => x.Location));

现在查询:
var point = GeoJson.Point(GeoJson.Geographic(-96.770401, 32.816774)); //long, lat

var locationClause = Query<Foo>.Near(y=> y.Location, point, 20); //20 is max distance from your question. note that it's in meters
IQueryable<Foo> query = collection.AsQueryable().Where( x=> locationClause.Inject());

//or with the non-generic Query:
IQueryable<Foo> query = collection.AsQueryable().Where( x=> Query.Near("Location", point, 20).Inject());

关于linq - C#MongoDB "Near"查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14398308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com