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 _id
s 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);
}
?>