Andre
Andre

Reputation: 1257

Query an ArrayPosition in MongoDB

I have a collection like this:

> db.nodes.find()  
{ "_id" : ObjectId("534d44e182bee8420ace927f"), "id" : "59598841", "created_by" : "JOSM", "geo" : { "type" : "Point", "coordinates" : [ 9.7346094, 52.371738 ] } }  
{ "_id" : ObjectId("534d44e182bee8420ace9280"), "id" : "59598842", "created_by" : "JOSM", "geo" : { "type" : "Point", "coordinates" : [ 9.7343616, 52.3718121 ] } }  
{ "_id" : ObjectId("534d44e182bee8420ace9281"), "id" : "59598845", "created_by" : "JOSM", "geo" : { "type" : "Point", "coordinates" : [ 9.7331504, 52.372057 ] } }  
{ "_id" : ObjectId("534d44e182bee8420ace9282"), "id" : "59835778", "created_by" : "JOSM", "geo" : { "type" : "Point", "coordinates" : [ 9.7354137, 52.3711697 ] } }  
{ "_id" : ObjectId("534d44e182bee8420ace9283"), "id" : "60409270", "created_by" : "JOSM", "geo" : { "type" : "Point", "coordinates" : [ 9.7354388, 52.3735999 ] } }  

Now I want to query the coordinates-array to find the document with the greatest lon-value. How can I do that, I have no idea :(

Tschüss, Andre

Upvotes: 2

Views: 51

Answers (2)

Lalit Agarwal
Lalit Agarwal

Reputation: 2354

Try using the aggregation framework

db.nodes.aggregate(
 { $unwind: "geo.coordinate" },
 { $group: { _id: { id: "$id"}, lon: { $first: "geo.coordinate" } } },
 { $group: { _id: null, maxval: { $max: "$lon" } } }
)

For more info on aggregation look here: http://docs.mongodb.org/manual/reference/operator/aggregation/

Upvotes: 0

Neil Lunn
Neil Lunn

Reputation: 151112

So actually getting the "lon" which is the first value, of the array may not seem immediately apparent, but is quite simple with aggregate:

db.nodes.aggregate([
    { "$project": {
        "_id": {
          "_id": "$_id",
          "id": "$id",
          "created_by": "$created_by",
          "geo": "$geo",
        },
        "coordinates": "$geo.coordinates"
    }},
    { "$unwind": "$coordinates" },
    { "$group": {
        "_id": "$_id",
        "lon": { "$first": "$coordinates" }
    }},
    { "$sort": { "lon": 1 } },
    { "$limit": 1 },   
    { "$project": {
        "_id": "$_id._id",
          "id": "$_id.id",
          "created_by": "$_id.created_by",
          "geo": "$_id.geo",
    }}
])

Which gives the whole document with the higest value. Or if you just want the value:

db.nodes.aggregate([
    { "$unwind": "$geo.coordinates" },
    { "$group": {
        "_id": "$_id",
        "lon": { "$first": "$geo.coordinates" }
    }},
    { "$group": {
        "_id": null,
        "lon": { "$max": "$lon" }
    }}
])

Upvotes: 2

Related Questions