如何使用NearSphere MongoDB驱动程序C#将距离结果返回到点 - c#

我有这个查询:

await collection.FindAsync(Builders<T>.Filter.NearSphere(s => plcace.Location, location.Longitude, location.Latitude)
& Builders<T>.Filter.Nin(s => s.Id, excludedIDList))

它按预期工作。

但是,除了结果以外,现在我想得到给定位置的点与作为结果返回的文档之间的距离。

我尝试了几种方法,例如https://oraerr.com/database/mongodb/c-mongodb-driver-2-0-getting-distance-back-from-near-query/

var coll = _database.GetCollection<UrbanEntity>("mycoll");
var geoNearOptions = new BsonDocument {
    { "near", new BsonDocument {
        { "type", "Point" }, 
        { "coordinates", new BsonArray {location.Longitude, location.Latitude} },
        } },
    { "distanceField", "dist.calculated" },
    { "maxDistance", 100 }, 
    { "includeLocs", "dist.location" },  
    { "num", 5 },  
    { "spherical" , true }
};

var pipeline = new List<BsonDocument>();
pipeline.Add( new BsonDocument { {"$geoNear", geoNearOptions} });

using(var cursor = await coll.AggregateAsync<BsonDocument>(pipeline)) {
    while(await cursor.MoveNextAsync()) {
        foreach (var doc in cursor.Current) {
            // Here you have the documents ready to read
        }
    }
}

但是,(在上面的示例之后),它始终仅返回4个文档。....我始终不确定它是如何工作的。即使maxDistance行被删除,我仍然拥有相同的文档。

是否可以使用Builders<T>而不是BsonDocument来建立聚合?另外,如何限制退回的文件数量?

谢谢

参考方案

我终于可以找到想要的东西(对ND的答案略作编辑):

public async Task<List<NearbyLocation>> GetNearbyLocationsAsync(Location location, int? take, List<ObjectId> exclude)
{
    var geoNearOptions = new BsonDocument {
        { "near", new BsonDocument {
            { "type", "Point" },
            { "coordinates", new BsonArray { location.Longitude, location.Latitude } }, } },
        { "query", new BsonDocument("_id", new BsonDocument("$nin", new BsonArray(exclude))) }, 
        // "query": Here you can add stuff to your geoNear aggregation. 
        // In fact, when I am searching around, I don't want a couple of IDs.
        { "distanceField", "distance" },
        { "limit", take },
        { "spherical", true}
        // I was first using $nearSphere because of spherical approach.
        // I then set the geoNear query as spherical by setting it to "true".
    };

    var pipeline = new List<BsonDocument>
    {
        new BsonDocument { { "$geoNear", geoNearOptions } },
        new BsonDocument( "$sort", new BsonDocument("distance", 1))
        // As per documentation, $nearSphere is sorting by distance.
        // As per my tests (maybe I am wrong), it wasn't sorted, so I added a sort option
        // to my aggregation.
    };

    List<NearbyLocation> locations = new List<NearbyLocation>();
    using (var cursor = await GetCurrentCollection().AggregateAsync<BsonDocument>(pipeline))
    {
        while (await cursor.MoveNextAsync())
        {
            foreach (var doc in cursor.Current)
            {
                double distanceInMeters = doc["distance"].ToDouble();
                NearbyLocation location = new NearbyLocation
                {
                    Location = (BsonSerializer.Deserialize<Location>(doc["location"].ToBson())),
                    KmDistance = distanceInMeters / 1000, // From meters to KMs
                    MileDistance = distanceInMeters * 0.000621371192 // From meters to Miles
                };
                locations.Add(location);
            }
        }
    }

    return locations;
}

幸运的是,在我的情况下,该位置是一个子文档,这意味着我仅使用它,而没有使用整个文档,否则,我得到反序列化错误..仍在处理它,但这是另一个问题。

我对反序列化有一个问题,因为distance字段实际上不是我的课程的一部分。.然后我正在考虑将生成的文档放入另一个字段,例如:

{
    "distance":0.1234,
    "location":{...}
}

当回复有时是一个对象有时是一个数组时,如何在使用改造时解析JSON回复? - java

我正在使用Retrofit来获取JSON答复。这是我实施的一部分-@GET("/api/report/list") Observable<Bills> listBill(@Query("employee_id") String employeeID); 而条例草案类是-public static class…

改造正在返回一个空的响应主体 - java

我正在尝试使用Retrofit和Gson解析一些JSON。但是,我得到的响应机构是空的。当我尝试从对象中打印信息时,出现NullPointerException。我确保URL正确,并且我也确保POJO也正确。我正在使用jsonschema2pojo来帮助创建POJO类。这是我要解析的JSON{ "?xml": { "@versi…

Div单击与单选按钮相同吗? - php

有没有一种方法可以使div上的click事件与表单环境中的单选按钮相同?我只希望下面的div提交值,单选按钮很丑代码输出如下:<input id="radio-2011-06-08" value="2011-06-08" type="radio" name="radio_date&#…

每个文件合并后添加换行 - python

我有很多类似以下内容的JSON文件:例如。1.json{"name": "one", "description": "testDescription...", "comment": ""} test.json{"name"…

将python scikit学习模型导出到pmml - python

我想将python scikit-learn模型导出到PMML。哪个python软件包最合适?我阅读了有关Augustus的内容,但是我无法使用scikit-learn模型找到任何示例。 python大神给出的解决方案 SkLearn2PMML是 JPMML-SkLearn命令行应用程序周围的薄包装。有关受支持的Scikit-Learn Estimator和…