简体   繁体   English

如何在MongoDB中查询具有特定条件的数组

[英]how to query array with specific condition in MongoDB

here's my mongodb object example 这是我的mongodb对象示例

{
    "_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 我已经在MongoHub上尝试了以下行,但是它给了我“无效的运算符:$和”味精

{"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. 例如,我想查询值大于-27的元素作为数组的第一个值。 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. 在这里也发现了相同的问题 ,但那是3年以前的,所以认为现在应该有更好的方法。

Thanks for reading my question. 感谢您阅读我的问题。

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). 因此0代表拳头位置(经度),而第二个位置(纬度)则使用1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM