1

I use this query to query NULL values as "0":

select * from myTable where IFNULL(field_id, 0) = 0

How do I achieve the same in MongoDB using PHP?

My code:

/**
 * @var MongoDB
 */
$db = $this->getMongoDbHandler();

/**
 * @var MongoCollection
 */
$coll = $db->selectCollection('myColl');

/**
 * @var MongoCursor
 */
$cursor = $coll->find($where);

How should I form $where array?

I guess I should do something like:

$where['field_id'] = [
    '$ifNull' => ['field_id', 0]
];

But where do I then indicate the required value?

Thanks!

1 Answer 1

1

Create a variable to hold the JavaScript function that returns the null coalescing expression. Here's some sample test documents to test this in mongo shell:

db.test.insert([
    { _id: 1, field_id: 0 },
    { _id: 2, test_field: 1 },
    { _id: 3, field_id: null },    
    { _id: 4, field_id: 3 }
])

I would expect my find query that uses the $where operator to return the documents with _ids 1,2 and 3, thus output for the query

db.test.find({ "$where": "function() { return (this.field_id || 0) == 0; }" })

would be

/* 0 */
{
    "_id" : 1,
    "field_id" : 0
}

/* 1 */
{
    "_id" : 2,
    "test_field" : 1
}

/* 2 */
{
    "_id" : 3,
    "field_id" : null
}

This PHP example demonstrates how to search a collection using javascript code to reduce the resultset using the same concept above:

<?php

/**
 * @var MongoDB
 */
$db = $this->getMongoDbHandler();

/**
 * @var MongoCollection
 */
$coll = $db->selectCollection('myColl');

/**
 * @var JavaScript code
 */
$js = "function() { return (this.field_id || 0) == 0; }" ;

/**
 * @var MongoCursor
 */ 
$cursor = $coll->find(array('$where' => $js));

foreach ($cursor as $doc) {
    var_dump($doc);
}

?>
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, most appreciated!

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.