【问题标题】:How do I query MongoDB from PHP with IFNULL() expression inside WHERE?如何在 WHERE 中使用 IFNULL() 表达式从 PHP 查询 MongoDB?
【发布时间】:2016-02-25 19:06:03
【问题描述】:

我使用此查询将 NULL 值查询为“0”:

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

如何在 MongoDB 中使用 PHP 实现相同的功能?

我的代码:

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

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

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

我应该如何形成$where数组?

我想我应该这样做:

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

但是我应该在哪里指明所需的值?

谢谢!

【问题讨论】:

    标签: php mongodb where ifnull


    【解决方案1】:

    创建一个变量来保存返回空合并表达式的 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);
    }
    
    ?>
    

    【讨论】:

    • 太棒了,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    相关资源
    最近更新 更多