Matt
Matt

Reputation: 3896

MongoDB equivalent of "NOT BETWEEN"

I'm using MongoDB, the PHP driver, and Google Maps. Since Google Maps does a wrap-around for Longitudes (the LEFT longitude could be greater than the RIGHT longitude in some cases), I'm trying to get the equivalent of MySQL's NOT BETWEEN working in MongoDB.

Has anyone successfully used the MongoDB "$or" operator to simulate NOT BETWEEN?

Here's my (unsuccessful) attempt so far:

// If the LEFT longitude is greater
if ($longitude_left > $longitude_right) {
    $params = array(
        '$or' => array(
            'longitude' => array('$gte' => $longitude_left, '$lte' => $longitude_right)
        )
    );
}
// By default, the RIGHT longitude is greater
else {
    $params = array(
        'longitude' => array(
            '$gte' => $longitude_left, '$lte' => $longitude_right
        )
    );
}

$mongo = new Mongo();
$cursor = $mongo->energy->plants->find($params);

Upvotes: 1

Views: 2736

Answers (2)

Justin Jenkins
Justin Jenkins

Reputation: 27080

MongoDB's PHP driver always accepts/expects arrays ...

Since you are passing arrays for $gte and $lte too ... both need to be in arrays for $or to work correctly.

In your example you pass the first part in an array but not an array for $or and 2 more arrays for $gte and $lte ...

For your example to work, you'll need to do something like ...

$params = array('$or' => array(
                     array('longitude' => array('$gte' => $longitude_left)),
                     array('longitude' => array('$lte' => $longitude_left))
                   )
           );

$cursor = $collection->find($params);

Upvotes: 3

user2665694
user2665694

Reputation:

NOT BETWEEN (a, b)

basically translates into

into an $or clause with

$lt a
$gt b

Converting this into a MongoDB JSON query syntax is straight forward. Or where is your problem?

Upvotes: 0

Related Questions