Eugene Yu
Eugene Yu

Reputation: 3958

how to query array with specific condition in MongoDB

here's my mongodb object example

{
    "_id": ObjectId("asdklfjasdlkfjal"),
    "geometry": {
        "type": "Point",
        "coordinates": [
            -26.62375,
            152.86114
        ]
    }
},
{
    "_id": ObjectId("asdklfjasdlkfjal2"),
    "geometry": {
        "type": "Point",
        "coordinates": [
            -28.62375,
            123.86114
        ]
    }
}

I have read the document here but it does not show me an option to query only the first element of the array.

I've tried the following line on MongoHub but it gives me "invalid operator: $and" msg

{"geometry.coordinates": {$and: [{$lt: -30, $gt: 151}, {$lt: -35, $gt: 151}]}}

For example, I'd like to query the elements that have the value greater than -27 as the first value of the array. So only the first example object should be pulled no matter what value the second element has in the array (or the other way around).

Also found the same question here but it was 3yrs ago so thought there should be a better way by now.

Thanks for reading my question.

Upvotes: 0

Views: 63

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151132

Not really the same as the question you referenced. Your "coordinates" are fixed to two positions, longitude and latitude. All you really need is "dot notation":

 db.collection.find({ "geometry.coordinates.0": { "$gt": -27 } })

So the 0 stands for the fist position (longitude) and you would use 1 for the second position (latitude).

Upvotes: 2

Related Questions