格式 MongoDB 查询输出

Format MongoDB Query output

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

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

不幸的是,returns 比 Google 地图 API 需要更多的信息。输出:

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

我想要的输出:

52.3746373, 4.85773855

我是 MongoDB 的新手,非常感谢任何建议。

使用 find() 最接近的是:

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

产生:

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

从那里您可以使用客户端处理 return "coordinates" 数组字段值。


您还可以使用 aggregate() method to do this. All you will need is $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 
    ))
));