Joost
Joost

Reputation: 41

Format MongoDB Query output

I'm currently running a MongoDB instance to save collected tweets within a geo-box in realtime. With that, I want to generate a heatmap to show where the most tweets were sent in Amsterdam. To do that I have to query the geo line only. That works with the following line of code:

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

Unfortunately, this returns more info then the Google Maps API needs. Output:

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

What I want as output:

52.3746373, 4.85773855

I'm quite new to MongoDB, so would really appreciate any suggestions.

Upvotes: 1

Views: 2824

Answers (1)

Sede
Sede

Reputation: 61225

The closest you can get using find() is:

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

which produces:

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

From there you use client-side processing to return the "coordinates" array field value.


You can also use the aggregate() method to do this. All you will need is $project your documents.

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

which yields something like:

{ "coordinates" : [ 52.3746373, 4.85773855 ] }

Translation in PHP gives:

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

Upvotes: 1

Related Questions