更新文档MongoDB PHP的值


Updating value of a document MongoDB PHP

在名为user_notifications的数据库中,每个用户都有一个带有用户id的集合。

应该有一个静态文档,其中包含一个计数器列,每个集合的默认值都设置为0。

在一个简单的方法调用中,我需要将计数器值增加1,作为MongoDB的新手,我认为我搞砸了。需要一些想法,这里是我的对象,可以做到这一点:

private function increment_notification()
{
    // database   => notification
    // collection => _238
    // document   => unseen_counter
    $unseen = $this->notification->_238->unseen_counter; // selecting a single document
    // if the document didn't exists then create the document and 
    // set a default value 0 to the counter row.
    if(!$unseen) {
        // create a new document
        $this->notification->insertOne([
            '_id' => 'unseen_counter',
            'counter' => '0'
        ]);
    } else {
        // we already have the document
        // now update the counter value by 1
        $unseen->update([
            '$set' => [
                'counter' => $unseen['counter'] + 1;
            ]
        ]);
    }
}

我最终把这个方法写成了一个伪代码:[

作为MongoDB的初学者,我的模式设计怎么样?有什么改进的建议吗?此外,我应该如何运行上述查询?

感谢

另一种方法是使用$inc运算符。以下是$inc的文档和示例。