gpt4 book ai didi

c# - 尝试使用mongodb的filter.near

转载 作者:太空宇宙 更新时间:2023-11-03 16:58:39 29 4
gpt4 key购买 nike

我正在尝试从嵌套的mongodb文档中找到最接近的编码。我不断收到的错误如下:

我已经尽力想了一切。我试图添加索引2d,但这两个都不起作用。

var point = GeoJson.Point(GeoJson.Geographic(38.8086, -85.1792));
var locationQuery = new FilterDefinitionBuilder<Book>().NearSphere(tag => tag.CitiesInBook[-1].Location, point,
5000);
var query = collection.Find(locationQuery).Limit(10);
var a = query.ToList();


规划器返回错误


  找不到$ geoNear查询的索引。”

最佳答案

以下汇总查询适用于图书实体中的嵌入式城市。需要注意的一点是,您应该使用正确的键名称创建geo2dsphere索引,并在正确的结构中使用c#类,以便驱动程序进行序列化/反序列化。

db.Book.aggregate({
"$geoNear": {
"near": {
"type": "Point",
"coordinates": [
48.857908,
2.295243
]
},
"distanceField": "SearchResult.DistanceKM",
"spherical": true,
"maxDistance": NumberInt("20000"),
"includeLocs": "SearchResult.Location"
}
})


上面的查询是由以下MongoDB.Entities代码生成的:

using MongoDB.Driver;
using MongoDB.Entities;
using System.Collections.Generic;

namespace StackOverflow
{
public class Program
{
public class Book : Entity
{
public string Title { get; set; }
public List<City> CitiesInBook { get; set; } = new List<City>();
public SearchResult SearchResult { get; set; }
}

public class City
{
public string Name { get; set; }
public Coordinates2D Location { get; set; }
}

public class SearchResult
{
public Coordinates2D Location { get; set; }
public double DistanceKM { get; set; }
}

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

//create a geo2dsphere index with key "CitiesInBook.Location"
DB.Index<Book>()
.Key(x => x.CitiesInBook[-1].Location, KeyType.Geo2DSphere)
.Create();

//create 3 locations
var paris = new City
{
Name = "paris",
Location = new Coordinates2D(48.8539241, 2.2913515)
};
var versailles = new City
{
Name = "versailles",
Location = new Coordinates2D(48.796964, 2.137456)
};
var poissy = new City
{
Name = "poissy",
Location = new Coordinates2D(48.928860, 2.046889)
};

//create a book and add two cities to it
var book = new Book { Title = "the power of now" };
book.CitiesInBook.Add(paris);
book.CitiesInBook.Add(poissy);
book.Save();

var eiffelTower = new Coordinates2D(48.857908, 2.295243);

//find all books that have places within 20km of eiffel tower.
var books = DB.GeoNear<Book>(
NearCoordinates: eiffelTower,
DistanceField: b => b.SearchResult.DistanceKM,
IncludeLocations: b => b.SearchResult.Location,
MaxDistance: 20000)
.ToList();
}
}
}

关于c# - 尝试使用mongodb的filter.near,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56367251/

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