创建一个变量来保存返回空合并表达式的 JavaScript 函数。这是一些示例测试文档,用于在 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 }
])
我希望我的 find 查询使用$where运算符返回带有_ids 1,2 和 3 的文档,从而输出查询
db.test.find({ "$where": "function() { return (this.field_id || 0) == 0; }" })
将会
/* 0 */
{
"_id" : 1,
"field_id" : 0
}
/* 1 */
{
"_id" : 2,
"test_field" : 1
}
/* 2 */
{
"_id" : 3,
"field_id" : null
}
这个 PHP 示例演示了如何使用 javascript 代码搜索集合以使用上述相同概念减少结果集:
<?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);
}
?>