11

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?

2 Answers 2

20

Yeah, you want the $ne operator, so

$cursor = $collection->find(array("someField" => array('$ne' => null)));
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Jim. I just tried to post the same answer... but I don't have enough rep yet. I will accept your answer as soon as it will let me.
@jim Should be single quotes because of the $.
whoops on single quotes...haven't written php in a long time
2

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.

2 Comments

Thanks Tim, I was wondering how to check whether or not the field exists.
@MichaelIrey Yeah, with schema-less databases, there is a difference between 'is it null' and 'does it exist'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.