2

我有这个查询:

db.places.aggregate([
   { "$geoNear" : 
      { "near" : 
         { 
            "type" : "Point", "coordinates" : [23, 11] 
         }, "distanceField" : "distance",
          "spherical" : true 
      } 
   },
   { 
      "$sort" : 
      { "distance" : 1 } 
   },
   { 
      "$limit" : 10 
   }
])

哪个会返回

{
    "_id":ObjectId("XXXX"),
    "longitude":23.11,
    "latitude":11.1995,
    "distance":23.111995
}

但是,在 C# 等语言中,由于“距离”不是返回文档的 C# 类的一部分,因此会中断反序列化。

我怎样才能得到如下结果?

{
    "document": {
        "_id":ObjectId("XXXX"),
        "longitude":23.11,
        "latitude":11.1995
    },
    "distance":23.111995
}

谢谢你的帮助

4

1 回答 1

2

您可以运行$project来重塑您的聚合结果。$$ROOT表示作为输入传递到管道阶段的文档:

db.places.aggregate([
    { "$geoNear" : { "near" : { "type" : "Point", "coordinates" : [23, 11] }, "distanceField" : "distance", "spherical" : true } },
    { "$sort" : { "distance" : 1 } },
    { "$limit" : 10 },
    { "$project:": { "document": "$$ROOT", "distance": 1 } },
    { "$project": { "document.distance": 0, "_id": 0 } }
])
于 2020-02-09T21:25:35.900 回答