【问题标题】:Format MongoDB Query output格式化 MongoDB 查询输出
【发布时间】:2016-05-21 13:27:43
【问题描述】:

我目前正在运行一个 MongoDB 实例,以便将收集到的推文实时保存在地理框中。有了这个,我想生成一个热图来显示在阿姆斯特丹发送最多推文的地方。为此,我只需要查询地理线。这适用于以下代码行:

db.testtweets.find({"geo": { "$ne": null } }, { "geo": 1 });

不幸的是,这会返回比 Google Maps API 需要的更多信息。输出:

{ "_id" : ObjectId("56fea2cf206e3712f3d1a9bb"), "geo" : { "type" : "Point", "coordinates" : [ 52.3746373, 4.85773855 ] } }

我想要的输出:

52.3746373, 4.85773855

我对 MongoDB 很陌生,所以非常感谢任何建议。

【问题讨论】:

    标签: php mongodb mongodb-query aggregation-framework mongodb-php


    【解决方案1】:

    使用find() 最接近的是:

    db.testtweets.find(
        { "geo": { "$ne": null } }, 
        { "geo.coordinates": 1, "_id": 0 }
    )
    

    产生:

    { "geo" : { "coordinates" : [ 52.3746373, 4.85773855 ] } }
    

    从那里您使用客户端处理来返回“坐标”数组字段值。


    您也可以使用aggregate() 方法来执行此操作。您只需要$project您的文件即可。

    db.testtweets.aggregate([ 
        { "$match": { "geo": { "$ne": null } } }, 
        { "$project": { 
            "coordinates": "$geo.coordinates", 
            "_id": 0 
        }}
    ]);
    

    产生类似的东西:

    { "coordinates" : [ 52.3746373, 4.85773855 ] }
    

    PHP 中的翻译给出:

    db.testtweets.aggregate(array( 
        array("$match" => array("geo" => array( "$ne" => null)), 
        array("$project" => array( 
            "coordinates" => "$geo.coordinates", 
            "_id" => 0 
        ))
    ));
    

    【讨论】:

    • 谢谢,它确实提供了您提到的输出。有什么办法只输出数字 52.3746373, 4.85773855?
    猜你喜欢
    • 2013-07-16
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多