2

I have this query:

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

Which would return

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

However, in languages such as C#, in breaks the deserialization as "distance" isn't part of returned document's C# class.

How would I be able to get the result like the following?

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

Thanks for any help

Emixam23
  • 3,854
  • 8
  • 50
  • 107

1 Answers1

2

You can run $project to reshape your aggregation result. $$ROOT represents the document that's being passed to a pipeline stage as input:

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 } }
])
mickl
  • 48,568
  • 9
  • 60
  • 89
  • Thanks for the answer. By reading, I can assume that `{ "$project:": { "document": "$$ROOT", "distance": 1 } }` means that we want to keep the ascending order right? But then, what `{ "$project": { "document.distance": 0, "_id": 0 } }` is doing with the value 0? Does it means that we put both of these values at level 0 (root) ? – Emixam23 Feb 10 '20 at 22:19
  • No, `1` means that I want to keep that field, `0` means that I'm getting rid of that field. I need to carry `distance` over to keep it separate from the root of the document – mickl Feb 10 '20 at 23:25