【问题标题】:Retrieve document with fields' value changed using another query检索使用另一个查询更改字段值的文档
【发布时间】:2018-01-28 08:27:06
【问题描述】:

我在我的国家/地区的 MongoDB 上有这个数据库,其中包含 OpenStreetMap 的数据,我使用 Node-Mongosm 导入它并生成三个集合:nodeswaysrelations

请求 Way 时,输出以下文档(来自 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 的功能还是错误),但我可以从nodes 字段中检索每个节点的坐标来填充它,即:节点445848963:

{
   "_id":445848963,
   "loc":{
      "type":"Point",
      "coordinates":[
         -83.5047254,
         10.0984515
      ]
   }
}

所以,我的问题是是否有可能以及我应该如何编写查询以从 ways 集合中收集文档,其中字段 coordinates 填充有节点(ways.loc.nodes field) 动态坐标,因此检索到的文档如下所示:

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

【问题讨论】:

    标签: mongodb


    【解决方案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
            ]
        }
    }
    

    【讨论】:

    • 为什么你从来没有引用nodes 集合来获取查询中way 文档的字段coordinates 的坐标,或者你使用coords 而不是nodes 作为集合的名称只是为了解释?
    • in $lookup from 有join collection name,即coorinatesequity join by loc.nodescoodinates._id,如果不同可以改成你的collection name
    猜你喜欢
    • 2019-07-31
    • 2011-02-06
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 2017-09-13
    • 1970-01-01
    相关资源
    最近更新 更多