Michael
Michael

Reputation: 3628

PHP Mongo Query NOT NULL

Anyone know the syntax for writing a php-mongo query to use NOT NULL?

I know how to do this when I query for NULL:

<?php
$cursor = $collection->find(array("someField" => null));

Is this even possible?

Upvotes: 11

Views: 15548

Answers (2)

jjm
jjm

Reputation: 6198

Yeah, you want the $ne operator, so

$cursor = $collection->find(array("someField" => array('$ne' => null)));

Upvotes: 20

Tim Lytle
Tim Lytle

Reputation: 17624

Basically, the same kind of queries you would use on the Mongo console, you pass as an array to the query methods.

In your case, it could be (if you're checking that the field exists - note that the field could just be absent from the document):

array("someField" => array('$exists' => true))

Or to check if it's not equal to null:

array("someField" => array('$ne' => null))

Watch out for the $ in double quotes, since PHP will consider that a variable.

Upvotes: 2

Related Questions