在$和内使用MongoDB $

时间:2015-01-24 15:52:47

标签: mongodb meteor

我正在尝试搜索位置附近的“地点”并符合其他一些标准:

var places = Places.find(
{
    $and :
    [
        { categories : placesCategory },

        {
            $or :
            [
                { name    : { $regex : searchQuery, $options : 'i' } },
                { city    : { $regex : searchQuery, $options : 'i' } },
                { country : { $regex : searchQuery, $options : 'i' } }
            ]
        },

        {
            location :
            {
                $near : [ nearLng, nearLat ],
                $maxDistance : 67.15 // radians
            }
        }
    ]
}).fetch();

然而,控制台告诉我“$ near不能在另一个$运营商内”。

有没有办法在$和?

中包含$ near

或者最佳做法是什么?

1 个答案:

答案 0 :(得分:0)

您不需要在$和声明中包含$ near查询。你可以把它放在外面,它会起作用。

var places = Places.find(
{
    location :
    {
        $near : [ nearLng, nearLat ],
        $maxDistance : 67.15 // radians
    },
    $and :
    [
        { categories : placesCategory },

        {
            $or :
            [
                { name    : { $regex : searchQuery, $options : 'i' } },
                { city    : { $regex : searchQuery, $options : 'i' } },
                { country : { $regex : searchQuery, $options : 'i' } }
            ]
        }
    ]
}).fetch();

但我不确定您的$ near查询是否正常工作。我更喜欢使用in' 2dsphere'更具体的查询。在坐标上。例如:

location:
{
    $near:
    {
        $geometry:
        {
            type: 'Point',
            coordinates: [ nearLng, nearLat ]
        },
        $maxDistance: 67.15 // radians
    }
}

编辑:要使用上述查询,请确保根据此模型保存数据:

location: {
    type: {
        type: String,
        enum: 'Point',
        default: 'Point'
    },
    coordinates: {
        type: [Number],
        default: [0,0],
        index: '2dsphere'
    }
}

当你想在矩形内找到位置时,你可能需要 $ box 运算符。这是一个示例搜索查询(请注意,我没有经验。您可能需要更改模型和/或添加索引以改进查询):

location: {
     $geoWithin: {
        $box: [
          [ <bottom left coordinates> ],
          [ <upper right coordinates> ]
        ]
     }
  }
}

请告诉我这是否有帮助!