使用其他查询检索字段值已更改的文档

时间:2018-01-28 08:27:06

标签: mongodb

我在MongoDB上有这个数据库,我的国家/地区有OpenStreetMap数据,我用Node-Mongosm导入它并生成三个集合:nodeswaysrelations。< / p>

请求方式时,输出以下文档(来自mongo shell):

{
   "_id":492464922,
   "tags":{
      "maxspeed":"20",
      "surface":"asphalt",
      "highway":"residential",
      "oneway":"yes",
      "name":"Avenida 1"
   },
   "loc":{
      "type":"Polygon",
      "coordinates":[

      ],
      "nodes":[
         445848963,
         4844871065,
         432568566
      ]
   }
}

字段coordinates由于我不知道的原因而为空(不确定这是来自Node-Mongosm的功能还是错误),但我可以填充它从{检索每个节点的坐标{1}}字段,即:node nodes

445848963

所以,我的问题是否可能,如何编写查询以从{ "_id":445848963, "loc":{ "type":"Point", "coordinates":[ -83.5047254, 10.0984515 ] } } 集合中收集文档,其中字段ways填充了节点' (coordinates字段)动态坐标 ,以便检索到的文档如下所示:

ways.loc.nodes

1 个答案:

答案 0 :(得分:1)

您可以使用聚合管道

db.ways.aggregate(
[
    {$lookup : {
        from : "coords",
        localField : "loc.nodes",
        foreignField : "_id",
        as : "loc.coordinates"
    }},
    {$addFields : {
            "loc.coordinates" : {
                $reduce : {
                  input : "$loc.coordinates.loc.coordinates", 
                  initialValue :[], 
                  in : { $concatArrays : ["$$this", "$$value"] }
                }
            }
        }
    }
]
).pretty()

结果

{
    "_id" : 492464922,
    "tags" : {
        "maxspeed" : "20",
        "surface" : "asphalt",
        "highway" : "residential",
        "oneway" : "yes",
        "name" : "Avenida 1"
    },
    "loc" : {
        "type" : "Polygon",
        "coordinates" : [
            -83.5047254,
            10.0984515
        ],
        "nodes" : [
            445848963,
            4844871065,
            432568566
        ]
    }
}